# -*- coding: utf-8 -
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton

from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.popup import Popup
from kivy.uix.label import Label
from kivy.loader import Loader
from kivy.uix.image import Image
from kivy.uix.image import AsyncImage
import plistlib
import os
from kivy.network.urlrequest import UrlRequest
from kivy.clock import Clock
from functools import partial
from kivy.uix.screenmanager import ScreenManager, Screen
#from urllib import quote
#import urllib
from kivy.core.window import Window
#from kivy.uix.rst import RstDocument
from kivy.uix.scrollview import ScrollView
from kivy.animation import Animation
from lxml import etree
from lxml.html import parse, tostring, fromstring, clean
from textwrap import wrap
#import string
#from kivy.graphics import Color, Rectangle
#from kivy.lang import Builder
from random import shuffle
#from kivy.factory import Factory
from kivy.uix.carousel import Carousel
#from kivy.utils import platform
from kivy.uix.settings import Settings, SettingItem, SettingsPanel, SettingTitle, SettingBoolean
from kivy.config import ConfigParser
from kivy.config import Config

#from kivy.uix.scatter import Scatter

from kivy.properties import StringProperty, ObjectProperty

import ssl
from httplib import HTTPSConnection
import urllib
from time import time

#from kivy.cache import Cache

#from kivy.input.motionevent import MotionEvent

#, ListProperty,        BooleanProperty, NumericProperty




#print "PLATFORM: ", platform()

#TODO:
# display warning if download time of catalog file and news file is very slow 
# [done] check for new files on server: http://stackoverflow.com/questions/5909/get-size-of-a-file-before-downloading-in-python
# [done] download all files
# [done, manual] automatic orientation
# [done, all] erase single/all files
# [done] add technical news to the feed - fix feed handling: http://stackoverflow.com/questions/5385821/python-lxml-objectify-checking-whether-a-tag-exists
# [done] display all news text
# [doesn't look good and doesn't work] generate swiping carousel for news dynamically (only add the next required item)
# when swiping carousel created, apply for products
# [colision between carousel and slider...] create better groups/fixtures navigation interface 



#if platform() =="android":
FILE_DOWNLOAD_PATH=os.getcwd()+"/download/"
DEFAULT_LINK="http://www.robe.cz"



#else:

TEMP_DOWNLOAD_PATH="download/"


if not os.path.exists(FILE_DOWNLOAD_PATH):
    os.makedirs(FILE_DOWNLOAD_PATH)

if not os.path.exists(TEMP_DOWNLOAD_PATH):
    os.makedirs(TEMP_DOWNLOAD_PATH)




clrseq=[1,0,1]
shuffle(clrseq)
coloroverlay=clrseq+[1]
coloroverlay=[0,.7,1,1]
imageoverlay=[1,1,1,1]


#print coloroverlay

Builder.load_string('''

<MyLabelLargeText>:
	font_size: 23
	halign: 'center'
	
	canvas.before:
		Color:
			rgb: 1, 1, 1 # your color here
		Rectangle:
			pos: self.pos
			size: self.size

<MyLabelWithBackground>:
	font_size: 21
	halign: 'left'
	
	canvas.before:
		Color:
			rgb: 1, 1, 1 # your color here
		Rectangle:
			pos: self.pos
			size: self.size


<MyLabelWithBackground2>:
	font_size: 16
	halign: 'left'
	
	canvas.before:
		Color:
			rgb: 0, .7, 1 # your color here
		Rectangle:
			pos: self.pos
			size: self.size

<ButtonOption>:
    halign: 'center'
    valign: 'bottom'
    font_size: '20sp'
    
    canvas.before:
		Color:
			rgb: 0, 0, 0 # your color here
		Rectangle:
			pos: self.pos
			size: self.size

    BoxLayout:
        pos: root.pos
        size: root.width,root.height*.235

		canvas.before:
			Color:
				rgba: 1, 1, 1,.5 # your color here
			Rectangle:
				pos: self.pos
				size: root.width,root.height*.235

        Label:
			#halign: 'left'
			#valign: 'bottom'
            #size_hint_x: .5
            #pos:root.pos
            #pos: root.x, root.y
            id: labellayout
            markup: True
            text: root.desc
            #text: '[color=999999]{0}[/color]'.format(root.desc)
            font_size: 20
            #center_x: root.width
            #text_size: root.width,30
            #'[color=000000]{0}[/color]

<Article_display>:

	BoxLayout:
		orientation:'vertical'
		pos: root.width-60,root.y + 90
		size: 200,200
		canvas.after:
			Color:
				rgb: (1, 1, 1)
			Rectangle:
				size: self.size
				pos: self.center_x+50, 100
			

<ButtonNaviTest>:
    canvas:
        Clear

        Color:
            rgba: self.background_color
        Ellipse:
            #border: self.border
            pos: self.pos
            size: self.size
            source: self.background_normal if self.state == 'normal' else self.background_down

        Color:
            rgba: 1,1,1,.9
        Ellipse:
            #border: self.border
            #pos: self.pos
			pos: self.x+3,self.y+3
			size: self.size[0]-6,self.size[1]-6

        Color:
            rgba: 0,.24,.34,1
        Ellipse:
            #border: self.border
            #pos: self.pos
			pos: self.x+8,self.y+8
			size: self.size[0]-16,self.size[1]-16
            
        Color:
            rgba: self.color
        Rectangle:
            texture: self.texture
            size: self.texture_size
            pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)


<ButtonNavi>:

    canvas:
        Clear

        Color:
            rgba: self.background_color
        BorderImage:
            border: self.border
            pos: self.pos
            size: self.size
            source: self.background_normal if self.state == 'normal' else self.background_down

        Color:
            rgba: 1,1,1,.9
        BorderImage:
            border: self.border
            pos: self.pos
			pos: self.x+3,self.y+3
			size: self.size[0]-6,self.size[1]-6

        Color:
            rgba: 0,.24,.34,1
        BorderImage:
            border: self.border
            pos: self.pos
			pos: self.x+8,self.y+8
			size: self.size[0]-16,self.size[1]-16
            
        Color:
            rgba: self.color
        Rectangle:
            texture: self.texture
            size: self.texture_size
            pos: int(self.center_x - self.texture_size[0] / 2.), int(self.center_y - self.texture_size[1] / 2.)





<ButtonOptionYT>:
    halign: 'center'
    valign: 'bottom'
    font_size: 20
    
    canvas.before:
		Color:
			rgb: 0, 0, 0 # your color here
		Rectangle:
			pos: self.pos
			size: self.size

<ButtonOptionFB>:
    halign: 'left'
    valign: 'bottom'
    font_size: 12
    font_color:1,1,1
    
    canvas.before:
		Color:
			rgb: .2, .3, .35 # your color here
		Rectangle:
			pos: self.pos
			size: self.size


<ToggleButtonMenuXXX>:
    halign: 'left'
    valign: 'bottom'
    font_size: 20
    font_color:1,1,1
    
    canvas.before:
		Color:
			rgb: .2, .3, .35 # your color here
		Rectangle:
			pos: self.pos
			size: self.size


<ToggleButtonMenu>:
    font_size: 20
	canvas:
		Clear
		Color:
			rgba: self.background_color
		BorderImage:
			border: self.border
			pos: self.pos
			size: self.size
			source: self.background_normal if self.state == 'normal' else self.background_down
		Color:
			rgba: self.color
		Rectangle:
			texture: self.texture
			size: self.texture_size
			pos: int(self.center_x - self.texture_size[0] / 2.)+dp(150), int(self.center_y - self.texture_size[1] / 2.)


<ButtonOptionPR>:
    halign: 'left'
    valign: 'bottom'
    font_size: 20
    font_color:1,1,1
    
    canvas.before:
		Color:
			rgb: .2, .3, .35 # your color here
		Rectangle:
			pos: self.pos
			size: self.size

			
<FullImage>:
    canvas.after:
        Color:
            rgb: (0, 0, 0)
        Rectangle:
            texture: self.texture
            size: self.size
            pos: self.center_x+50, 100

<ItemButtonImage>:
    canvas:
        Color:
            rgba: self.color
        Rectangle:
            texture: self.texture
            size: self.norm_image_size
            pos: (self.center_x - self.norm_image_size[0] / 2.), self.center_y - self.norm_image_size[1] / 2.


#<ArticleImage>:
#    canvas.before:
#        Color:
#            rgb: (0, 0, 0)
#        Rectangle:
#            texture: self.texture
#            size: self.size
#            #pos: self.center_x+50, 100
            
<ArticleImage>:
    canvas.before:
        Color:
            rgb: (1, 1, 1)
        Rectangle:
			size: self.size
			pos: self.pos
            Color:
				rgb: (1, 1, 1)

<ButtonFB>:
    font_size: 20
	canvas:
		Clear
		Color:
			rgba: self.background_color
		BorderImage:
			border: self.border
			pos: self.pos
			size: self.size
			source: self.background_normal if self.state == 'normal' else self.background_down
		Color:
			rgba: self.color
		Rectangle:
			texture: self.texture
			size: self.texture_size
			pos: int(self.center_x - self.texture_size[0] / 2.)+dp(110), int(self.center_y - self.texture_size[1] / 2.)


            
<ButtonMenu>:
    font_size: 20



<ItemButton>:
    font_size: 20
    text_size: self.width, None
	canvas:
		Clear
		Color:
			rgba: self.background_color
		BorderImage:
			border: self.border
			pos: self.pos
			size: self.size
			source: self.background_normal if self.state == 'normal' else self.background_down
		Color:
			rgba: self.color
		Rectangle:
			texture: self.texture
			size: self.texture_size
			pos: int(self.center_x - self.texture_size[0] / 2)+dp(120), int(self.center_y - self.texture_size[1] / 2.)


<Tlacidlo>:
    BoxLayout:
        Button:
			text:"aaa"
			font_size: 20
			text_size: self.width, None
			pos:0,0
			canvas:
				Clear
				Color:
					rgba: self.background_color
				BorderImage:
					border: self.border
					pos: self.pos
					size: self.size
					source: self.background_normal if self.state == 'normal' else self.background_down
				Color:
					rgba: self.color
				Rectangle:
					texture: self.texture
					size: self.texture_size
					#pos: int(self.center_x - self.texture_size[0] / 2), int(self.center_y - self.texture_size[1] / 2.)
					


        Image:
			source:'web-ico.png'
			pos:0,0
			canvas:
				Color:
					rgba: self.color
				Rectangle:
					texture: self.texture
					size: self.norm_image_size
					#pos: self.center_x - self.norm_image_size[0] / 2., self.center_y - self.norm_image_size[1] / 2.
            
            
#<ToggleButtonMenu>:
#    font_size: 20
    
<WhiteCanvas>:
	canvas.before: 
		Color: 
			rgb: 1, 1, 1
		Rectangle:
			pos: self.pos
			size: self.size
<WhiteCanvas2>:
	canvas.before: 
		Color: 
			rgb: 1, 1, 1
		Rectangle:
			pos: self.pos
			size: self.size
		
<WhiteCanvasFloat>:
	canvas.before: 
		Color: 
			rgb: 0, .24, .34
		Rectangle:
			pos: self.pos
			size: self.size



<SettingMyItem>:
    size_hint: .25, None
    height: labellayout.texture_size[1] + dp(10)
    content: content
    canvas:
        Color:
            rgba: 47 / 255., 167 / 255., 212 / 255., 0
        Rectangle:
            pos: self.x, self.y + 1
            size: self.size
        Color:
            rgb: .2, .2, .2
        Rectangle:
            pos: self.x, self.y - 2
            size: self.width, 1

    BoxLayout:
        pos: root.pos

        Label:
            size_hint_x: .66
            id: labellayout
            markup: True
            text: '{0}\\n[size=13sp][color=999999]{1}[/color][/size]'.format(root.title or '', root.desc or '')
            font_size: '15sp'
            text_size: self.width - 32, None

        BoxLayout:
            id: content
            size_hint_x: .33


##[ThumbnailedListItem@SelectableView+BoxLayout]:
    #index: ctx.index
    #fruit_name: ctx.text
    #size_hint_y: .1
##    size_hint_y: ctx.size_hint_y
    
    
    #height: 150
##    ListItemLabel:
        #index: ctx.index
##        text: ctx.text
##		canvas:
##			Rectangle:
##				source: "download/{0}.jpg".format(ctx.text)
##				pos: self.x+10,self.y+6
##				size: 90,90
				#texture: self.texture
			#	Color:
			#		rgb: 1, 1, 1
			#	Rectangle:
			#		texture: self.texture
			#		pos: self.center_x - self.texture_size[0] / 2., self.center_y - self.texture_size[1] / 2.
			#		size: self.texture_size

<MySettings>:
    content: content
    menu: menu

    canvas:
        Color:
            rgb: 0, 0, 0
        Rectangle:
            pos: self.pos
            size: self.size

    FloatLayout:
        size_hint_x: None
        width: '100dp'
        GridLayout:
            pos: root.pos
            cols: 1
            id: menu
            orientation: 'vertical'
            padding: 5

            canvas.after:
                Color:
                    rgb: .2, .2, .2
                Rectangle:
                    pos: self.right - 1, self.y
                    size: 1, self.height

        Button:
            text: 'Close'
            size_hint: None, None
            width: '80dp'
            height: max(50, self.texture_size[1] + dp(20))
            pos: root.x + dp(10), root.y + dp(10)
            on_release: root.dispatch('on_close')
            font_size: '15sp'

    ScrollView:
        do_scroll_x: False
        id: sv
        Scatter:
            size_hint: None, None
            size: content.size
            do_translation: False
            do_rotation: False
            do_scale: False
            StackLayout:
                id: content
                height: self.minimum_height
                width: sv.width


''')

class ButtonNavi(Button):
	pass

class Tlacidlo(BoxLayout):
	pass
	

class FBImage(AsyncImage):
	pass

class MySettings(Settings):
	pass

class SettingMyItem(FloatLayout):
	title = StringProperty('<No title set>')
	desc = StringProperty(None, allownone=True)	
	content = ObjectProperty(None)
	def add_widget(self, *largs):
		if self.content is None:
			return super(SettingMyItem, self).add_widget(*largs)
		return self.content.add_widget(*largs)

class WhiteCanvas(GridLayout):
	pass
class WhiteCanvas2(BoxLayout):
	pass

class WhiteCanvasFloat(FloatLayout):
	pass


#class ArticleImage(Image):
#	pass
class MyImage(Image):
	def update(self,value):
		#print "update", value
		try:
			self.source=value
		except:
			pass

class ItemButtonImage(Image):
	def update(self,value):
		#print "update", value
		try:
			self.source=value
		except:
			pass


class MyItemImage(Image):
	def update(self,value):
		#print "update", value
		try:
			self.source=value
		except:
			pass

	def __init__(self, **kwargs):
		self.register_event_type('on_press')
		super(MyItemImage, self).__init__(**kwargs)

	def on_press(self):
		pass

	def on_touch_down(self, touch):
		if super(MyItemImage, self).on_touch_down(touch):
			return True
		if 'image' in touch.profile and touch.image in (
				'scrolldown', 'scrollup'):
			return False
		if not self.collide_point(touch.x, touch.y):
			return False
		if self in touch.ud:
			return False
		touch.grab(self)
		touch.ud[self] = True
		#self._do_press()
		self.dispatch('on_press')
		return True


class ArticleImage(Image):
	def update(self,value):
		#print "update", value
		self.source=value
	def __init__(self, **kwargs):
		self.register_event_type('on_press')
		super(ArticleImage, self).__init__(**kwargs)

	def on_press(self):
		pass

	def on_touch_down(self, touch):
		if super(ArticleImage, self).on_touch_down(touch):
			return True
		if 'image' in touch.profile and touch.image in (
				'scrolldown', 'scrollup'):
			return False
		if not self.collide_point(touch.x, touch.y):
			return False
		if self in touch.ud:
			return False
		touch.grab(self)
		touch.ud[self] = True
		#self._do_press()
		self.dispatch('on_press')
		return True


class FullImage(MyImage):
    pass

class WhiteLabel(Label):
    pass
    
class MyLabelLargeText(Label):
	pass

class MyLabelWithBackground(Label):
    def on_touch_down(self, touch):
        userdata = touch.ud
        if touch.is_double_tap:
			#print self.font_size
			if self.font_size<22:
				self.font_size+=6
			else:
				self.font_size-=6

class MyLabelWithBackground2(Label):
	pass

class ButtonOption(Button):
	desc=StringProperty('<unset>')

	def update(self,value):
		#print "update", value
		try:
			self.background_normal=value
		except:
			pass
	
	def __init__(self, **kwargs):
		super(ButtonOption, self).__init__(**kwargs)


class Article_display(BoxLayout):
	pass



class ButtonOptionFB(Button):
	pass

class ButtonOptionPR(Button):
	pass

class ButtonOptionYT(Button):
	desc=StringProperty('<unset>')

	def update(self,value):
		#print "update", value
		self.background_normal=value
	
	def __init__(self, **kwargs):
		super(ButtonOptionYT, self).__init__(**kwargs)

class save_info():
	#desc=StringProperty('<unset>')

	def __init__(self, *kwargs):
		#print "saving", kwargs
		result=str(kwargs[0].encode('utf-8')) + "," + str(int(time()))
		#print result
		f = open('info.txt','a')
		f.write(str(result) + "\n")
		f.close()

		

class ButtonMenu(Button):
	def update(self,value):
		#print "update", value
		try:
			self.background_normal=value
		except:
			pass


class ItemButton(Button):
	def update(self,value):
		#print "update", value
		try:
			self.background_normal=value
		except:
			pass


class ButtonFB(Button):
	pass
	
class ToggleButtonMenu(ToggleButton):
	def update(self,value):
		#print "update", value
		try:
			self.background_normal=value
		except:
			pass


class Boxy(GridLayout):
	pass

# Create the screen manager



menu=(Screen(name='menu'))
submenu=(Screen(name='submenu'))
itemmenu=(Screen(name='itemmenu'))
topmenu=(Screen(name='topmenu'))
article=(Screen(name='article'))
calendar=(Screen(name='calendar'))
catalogs=(Screen(name='catalogs'))
fb=(Screen(name='fb'))



sm = ScreenManager()
sm.add_widget(topmenu)
sm.add_widget(menu)
sm.add_widget(submenu)
sm.add_widget(itemmenu)
sm.add_widget(article)
sm.add_widget(calendar)
sm.add_widget(catalogs)
sm.add_widget(fb)

root=sm

#root=GridLayout(cols=1)

class MyUrlRequest2(UrlRequest):
	def __init__(self,*a,**k):
		if 'widget' in k:
			widget=k.pop('widget')
		else:
			widget=a.pop()
		if 'head' in k:
			head=k.pop('head')
		else:
			head=a.pop()
			
			
		UrlRequest.__init__(self,*a,**k)
		self.widget=widget
		self.head=head
		
			
	
class MyUrlRequest(UrlRequest):
	def __init__(self,*a,**k):
		if 'widget' in k:
			widget=k.pop('widget')
		else:
			widget=a.pop()
			
		UrlRequest.__init__(self,*a,**k)
		self.widget=widget


class News(BoxLayout):
	


	def CreateFB(self):
		root.wifb.clear_widgets()
		
		def move_fb(*args):
			try:
			
				root.lst=root.mynews.parsefbfile()
				root.lst.reverse()
				#print root.lst
				def rrr(*args):
					
					#print len(root.lst)
					if len(root.lst)!=0:
						txt,url,tp,likes,comments,pict,message,tstamp=root.lst.pop()
					else:
						try:
							root.lst=root.mynews.parsefbfile()
							root.lst.reverse()
							txt,url,tp,likes,comments,pict,message,tstamp=root.lst.pop()
						except:
							exit

					if txt=='':
						txt=message
					
					if len(txt)>2:
					
						txt=txt.replace('\n',' ')
						if len(txt)>90:
							txt=txt[0:90]+u'…'
						
						#import unicodedata
						#tyt=unicodedata.normalize(txt).encode('ascii','ignore')
						#txt.encode('ascii','ignore')
						#txt.decode('unicode-escape')
						anim = Animation(color=(1,1,1,0),duration=1) 
						#anim = Animation(pos=(-80,0),duration=5) 
						#anim = Animation(size=(10,30),duration=5) 
						anim.start(fblabel)
						def rpl(*args):
							fblabel.text='FB: '+txt


							
							#fblabel.bind(on_press=aaa)
				
							
							
							#print str(len(txt)) + ': ' +txt
							anim2 = Animation(color=(1,1,1,1), duration=1) 
							#anim2 = Animation(pos_hint('x':0, 'y':0), duration=.5) 
							anim2.start(fblabel)
							#anim2.bind(on_complete=rrr)
							Clock.schedule_once(partial(rrr), 5)
							

						#rpl()
						anim.bind(on_complete=rpl)
					else:
						rrr()

				
				rrr()
			except:
				exit
			
		
		top=BoxLayout()
		
		fbcnt=BoxLayout()
		
		#fbimg=FloatLayout()
			
		#img=Image(source='fb.png', size_hint=(1,1),pos_hint={'x':.48, 'y':0})
		
		#fbimg.add_widget(img)
		
		#cntin=FloatLayout(pos_hint={'x':0, 'y':0})

		#fblabel=ButtonOptionFB(text="",background_color=coloroverlay, text_size=(Window.width-20,None))
		
		fblabel=ButtonOptionFB(text="",background_color=coloroverlay,
		halign='left', font_size='14sp',font_color=[1,0,1,1],
		text_size=(Window.width-20,None),width=Window.width,
		)

		fblabel.bind(on_press=self.display_fb)
		
		#print Window.width
		#cntin.add_widget(fblabel)
		fbcnt.add_widget(fblabel)
		move_fb()

		top.add_widget(fbcnt)
		#top.add_widget(fbimg)
		
		root.wifb.add_widget(top)

		


	def CreateCalendar(self):
		#sm.current='calendar'
		#print ".............."
		calendar.content.clear_widgets()

		def openweb(url):
			save_info("menu-opencalweb")
			url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)
			
			import webbrowser
			webbrowser.open(url) 


		def opencalTest(i):
			import time
			#url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_EDIT)
			#intent.setType('vnd.android.cursor.item/event')
			#intent.putExtra("eventLocation",i[2])
			#intent.putExtra("description",i[1])
			
			#intent.putExtra("title",i[0] + " " + i[3])
			
			#print i[3]
			try:

				casti = i[3].split(' ')
				year=i[4]
				if len(casti)==2:
					day1=casti[0].replace('st','').replace('th','')
					month1=casti[1]
					day2=casti[0].replace('st','').replace('th','')
					month2=casti[1]
					
					print day1, month1
				if len(casti)==4:
					day1=casti[0].replace('st','').replace('th','')
					month1=casti[3]
					day2=casti[2].replace('st','').replace('th','')
					month2=casti[3]
					print day1, month1, day2, month2
				if len(casti)==5:
					day1=casti[0].replace('st','').replace('th','')
					month1=casti[1]
					day2=casti[3].replace('st','').replace('th','')
					month2=casti[4]
					print day1, month1, day2, month2
					
				fulldatea="%s %s %s" % (day1,month2,year)
				fulldateb="%s %s %s" % (day1,month2,year)
				a= time.mktime((time.strptime(fulldatea,"%d %B %Y")))*1000
				b= time.mktime((time.strptime(fulldateb,"%d %B %Y")))*1000
				print a,b
				#intent.putExtra("beginTime", 1198628984102);
				
				#intent.putExtra("beginTime", "1273791600000")
				#intent.putExtra("endTime", 1198628984102);
				
			except:
				pass
			
			
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)

		def opencal(i):
			#url=url
			#print "open ", url
			save_info("menu-opencalapp")
			from jnius import cast
			from jnius import autoclass
			#import time
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			intent = Intent()
			intent.setAction(Intent.ACTION_EDIT)
			intent.setType('vnd.android.cursor.item/event')
			intent.putExtra("description",i[1])
			intent.putExtra("eventLocation",i[2])
			#time.strptime('22 November 2013',"%d %B %Y")
			#try:
				
			#except:
			#	pass
			
			#intent.putExtra("allDay", True)
			intent.putExtra("title",i[0] + " " + i[3])
			
			#intent.setData(Uri.parse(url))
			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)


		def parsecalfile():
			#print "parsinf"
			from lxml import etree	
			#from lxml.html import parse, tostring, fromstring, clean

			out=[]
			feed = open("cal.txt", mode="r")
			feed = etree.parse(feed,etree.HTMLParser())
			feed = feed.getroot()


			for element in feed.iter('tbody'):
				#if element.get('class') == 'news-latest-item':
				txt=[]
				#print len(element), element
				meta = element.getchildren()
				#print element
				
				for tag in meta:
					place = tag[1].text
					date  = tag[2].text
					year  = tag[3].text
					exhib  = tag[0][0].text
					url   = tag[0][0].attrib.get('href')
					
					entry = [exhib,url,place,date,year]
			
					out.append(entry)

			return out

		
		scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
		content=GridLayout(cols=1, spacing=0, size_hint_y=None)
		content.bind(minimum_height=content.setter('height'))

			
		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wit.add_widget(topimg)
		content.add_widget(wit)

		contentins=GridLayout(cols=1, spacing=0, size_hint_y=None)
		contentins.bind(minimum_height=contentins.setter('height'))
		content.add_widget(contentins)

		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wib.add_widget(botimg)
		content.add_widget(wib)
			

		scroll.add_widget(content)
		
		def presss(scroll,where):
			if where < 0.000:
			#wit.size=(Window.width,0)
				print where,scroll.bar_width
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				print where,scroll.bar_width
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)
		
		calendar.add_widget(scroll)	 

		root.must_create_calendar=0

		wida=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imageweb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		wida.add_widget(imageweb)
		contentins.add_widget(wida)

		def go(*args):
			contentins.remove_widget(wida)


			
			items=parsecalfile()

			for i in items:
				btntext="[b]%s[/b] %s\n%s %s" % (i[0], i[2], i[3], i[4])
				btn=ButtonMenu(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='left',text_size=(Window.width-20, None),markup=True)
				
				btn.text=btntext
				
				#btn.text_size=200,None
				#btn.text_size=btn.width,None
				
				#lbl=MyLabelWithBackground2(text='aaAAbbBB',size_hint=(1, .20),pos_hint={'x':0, 'y':.8})
				#btn.bind(on_press=lambda widget, items=i[1]: openweb(items))
				#btn.bind(on_press=lambda widget, items=i: opencal(items))
				wid=FloatLayout(size_hint_y=None, size=(Window.width,110), background_color=coloroverlay)
				
				#print i['title']
				imageweb=MyImage(source="web-ico.png", background_color=coloroverlay, size_hint=(.6, .6),pos_hint={'x':.4, 'y':.16})
				imagecalendar=MyImage(source="cal-ico.png", background_color=coloroverlay, size_hint=(.6, .6),pos_hint={'x':.3, 'y':.2})
				
				btncalendar=Button(size_hint=(.09,.6), pos_hint={'x':.555, 'y':.18},background_color=[0,0,0,0])
				btnweb=Button(size_hint=(.09,.6), pos_hint={'x':.655, 'y':.18},background_color=[0,0,0,0])

				btncalendar.bind(on_press=lambda widget, items=i: opencal(items))
				btnweb.bind(on_press=lambda widget, items=i[1]: openweb(items))
				wid.add_widget(btn)
				wid.add_widget(btncalendar)
				wid.add_widget(btnweb)
				
				wid.add_widget(imageweb)
				wid.add_widget(imagecalendar)
				
				
				
				#wid.add_widget(lbl)
				
				
				contentins.add_widget(wid)
			
		Clock.schedule_once(partial(go), .8)



		
	def CreateFaceBook(self):
		#sm.current='calendar'
		#print ".............."
		fb.content.clear_widgets()

		def openweb(url):
			save_info("menu-openfbookweb")
			url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)

			import webbrowser
			webbrowser.open(url) 


	
		scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
		content=GridLayout(cols=1, spacing=0, size_hint_y=None)
		content.bind(minimum_height=content.setter('height'))
		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wit.add_widget(topimg)
		content.add_widget(wit)

		contentins=GridLayout(cols=1, spacing=0, size_hint_y=None)
		contentins.bind(minimum_height=contentins.setter('height'))
		content.add_widget(contentins)

		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wib.add_widget(botimg)
		content.add_widget(wib)
			

		scroll.add_widget(content)
		
		def presss(scroll,where):
			if where < 0.000:
			#wit.size=(Window.width,0)
				#print where,scroll.bar_width
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				#print where,scroll.bar_width
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)
		
		fb.add_widget(scroll)	 
		root.must_create_fb=0
		
		wida=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imageweb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		wida.add_widget(imageweb)
		contentins.add_widget(wida)

		
		def go(*args):
			
			items=root.mynews.parsefbfile()
			contentins.remove_widget(wida)
			

			for i in items:
				#txt,url,tp,likes,comments,pic, message
				
				cmnts=''
				if int(i[4])>0:
					cmnts=", comments: " + str(i[4])
					
				lks=''
				if int(i[3])>0:
					lks=", likes: " + str(i[3])
				

				btntext="%s[size=14]\n%s\n%s, %s%s%s[/size]" % (i[0].replace(' - ROBE lighting','').replace('ROBE lighting - ',''),i[6],i[7][0:10] + " " +i[7][11:16] ,i[2],lks,cmnts)
				
				btn=ButtonFB(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='left',text_size=(Window.width-30, None),markup=True)
				#btn=Tlacidlo(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='left',text_size=(Window.width-20, None),markup=True)
				#btn=Tlacidlo(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='left',text_size=(Window.width-20, None),markup=True)
				#print "..."
				#btn=ButtonMenu(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':.4, 'y':.16},halign='left',text_size=(Window.width-20, None),markup=True)
				btn.text=btntext
				pic_src=i[5]
				
				#if i[5]=='':
				#	pic_src="https://graph.facebook.com/127423910605493/picture"
				#	#pic_src="https://fbcdn-profile-a.akamaihd.net/hprofile-ak-snc6/276416_127423910605493_1020674032_q.jpg"
				#imageweb=FBImage(source=pic_src, background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':.008, 'y':.05},allow_stretch=True)
				imageweb=FBImage(source=pic_src, background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':.008, 'y':.05},allow_stretch=False)
				

				#btn.text_size=200,None
				#btn.text_size=btn.width,None
				
				#lbl=MyLabelWithBackground2(text='aaAAbbBB',size_hint=(1, .20),pos_hint={'x':0, 'y':.8})
				btn.bind(on_press=lambda widget, items=i[1]: openweb(items))
				#btn.bind(on_press=lambda widget, items=i: opencal(items))
				wid=FloatLayout(size_hint_y=None, size=(Window.width,110), background_color=coloroverlay)
				#wid=BoxLayout(orientation='horizontal', background_color=coloroverlay)
				
				#print i['title']
				
				wid.add_widget(btn)
				
				if pic_src<>'':
					pass
					wid.add_widget(imageweb)
				
				
				
				
				
				#wid.add_widget(lbl)
				
				
				contentins.add_widget(wid)

		Clock.schedule_once(partial(go), .8)
		#content.add_widget(ins)


	def display_gobos_a(self,items):
		sm.current='gobos'
		#print ".............."
		gobos.content.clear_widgets()

		def parsegobofile():
			#print "parsinf"
			from lxml import etree
			#from lxml.html import parse, tostring, fromstring, clean

			out=[]
			feed = open("gobos.txt", mode="r")
			feed = etree.parse(feed,etree.HTMLParser())
			feed = feed.getroot()


			for element in feed.iter('a'):
				#	url   = tag[0][0].attrib.get('href')
				import re
				match=re.search('.jpg',element.text)
				if match:
					gobo=element.text
					gobo_name=element.text.replace('.jpg','')
					entry = gobo_name
					#print entry
					out.append(gobo_name)

			return out


		def on_progress2(req, cur_sz, tot_sz):
			
			#print "headers ", req.resp_headers
			#print "status ", req.resp_status
			
			#print tot_sz
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success2(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			
			#print req.resp_status
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
			#image=MyImage(source="b/"+url.split('/')[-1])
				req.widget.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				req.widget.update("fail.png")

		def on_error2(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			req.widget.update("logo.png")

		from kivy.adapters.simplelistadapter import SimpleListAdapter
		from kivy.uix.listview import ListView
		
		items=parsegobofile()
		
		image_list_item_args_converter = lambda row_index, rec: {'text': rec, 'size_hint_y': None, 'height': 32}
		
		wrap=GridLayout(cols=3)
		
		gobo_list_adapter = SimpleListAdapter(
			data=items, 
			args_converter=image_list_item_args_converter,
			template='ThumbnailedListItem',
			scrolling=True)
			
			
			
			
			

		#list_view = ListView(adapter=simple_list_adapter)		
		
		#def image_list_item_args_converter(row_index, rec):
		#	print rec, row_index

		#gobo_list_adapter = \
         #       SimpleListAdapter(
                    #sorted_keys=items,
          #          data=items,
           #         args_converter=image_list_item_args_converter,
            #        selection_mode='none',
                    #allow_empty_selection=False,
                    #template='ThumbnailedListItem')
                    
                    
					#[ThumbnailedListItem@SelectableView+BoxLayout]:
					#index: ctx.index
					#fruit_name: ctx.text
					#size_hint_y: ctx.size_hint_y
					#height: 150
					#Image
				#	#	source: "download/{0}.jpg".format(ctx.text)
					#ListItemButton:
				#		index: ctx.index
				#		text: ctx.text

                    
		gobo_list_view = \
				ListView(adapter=gobo_list_adapter)


        #self.add_widget(fruits_list_view)



		
		wrap.add_widget(gobo_list_view)
		gobos.add_widget(wrap)	 
		#|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
	
	def display_gobos(self,items):
		sm.current='gobos'
		#print ".............."
		gobos.content.clear_widgets()


		def parsegobofile():
			#print "parsinf"
			from lxml import etree
			#from lxml.html import parse, tostring, fromstring, clean

			out=[]
			feed = open("gobos.txt", mode="r")
			feed = etree.parse(feed,etree.HTMLParser())
			feed = feed.getroot()


			for element in feed.iter('a'):
				#	url   = tag[0][0].attrib.get('href')
				import re
				match=re.search('.jpg',element.text)
				if match:
					gobo=element.text
					gobo_name=element.text.replace('.jpg','')
					entry = [gobo, gobo_name]
					#print entry
					out.append(entry)

			return out


		def on_progress2(req, cur_sz, tot_sz):
			
			#print "headers ", req.resp_headers
			#print "status ", req.resp_status
			
			#print tot_sz
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success2(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			
			#print req.resp_status
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
			#image=MyImage(source="b/"+url.split('/')[-1])
				req.widget.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				req.widget.update("fail.png")

		def on_error2(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			req.widget.update("logo.png")


		items=parsegobofile()
		
		scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
		content=GridLayout(cols=6, spacing=0, size_hint_y=None)
		content.bind(minimum_height=content.setter('height'))
		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		#topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		#wit.add_widget(topimg)
		#content.add_widget(wit)
		idx=0
		for i in items:
			idx+=1
			if idx > 48:
				break
			#print i
			btntext="\n\n\n\n\n\n%s" % (i[1])
			btn=ButtonMenu(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='left',text_size=(90, None),markup=True)
			
			btn.text=btntext

			image=MyImage(source='image-loading.gif', background_color=coloroverlay, size_hint=(.7, .7),pos_hint={'x':.15, 'y':.25})

			#print items['smlImageUri']
			url="http://robe.cz/fileadmin/robe/downloads/dmx_charts/gobo_images/"+ i[0]
			url=url.replace(' ','_')
			if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
				image.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
			#p=self.q.push([url, "b/"+url.split('/')[-1]])
				#print imagetop
				try:
					self.reqcntr=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success2,\
						on_progress = on_progress2,\
						on_error = on_error2,\
						widget=image)
				except:
					pass	


			
			wid=FloatLayout(size_hint_y=None, size=(Window.width,150), background_color=coloroverlay)
			
			wid.add_widget(btn)
			#wid.add_widget(lbl)
			
			wid.add_widget(image)
			
			content.add_widget(wid)


		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		#botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		#wib.add_widget(botimg)
		#content.add_widget(wib)
			

		scroll.add_widget(content)
		
		def presss(scroll,where):
			if where < 0.000:
			#wit.size=(Window.width,0)
				#print where,scroll.bar_width
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				#print where,scroll.bar_width
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)
		
		gobos.add_widget(scroll)	 

	def display_calendar(self,widget):

		save_info("menu-calendar")
		
		if root.must_create_calendar==1:
			root.mynews.CreateCalendar()
		
		sm.current='calendar'

	def display_fb(self,widget):

		save_info("menu-fbook")
		
		if root.must_create_fb==1:
			root.mynews.CreateFaceBook()
		
		sm.current='fb'


	def display_catalogs(self,widget):
		
		save_info("menu-catalogs")

		if root.must_create_catalogs==1:
			root.mynews.CreateCatalogs()

		sm.current='catalogs'
	
	def CreateCatalogs(self):
		#sm.current='catalogs'
		#print ".............."
		catalogs.content.clear_widgets()




		def parsecatalogfile():
			from lxml import etree
			out=[]
			feed = open("catalogs.txt", mode="r")
			feed = etree.parse(feed,etree.HTMLParser())
			feed = feed.getroot()


			for element in feed.iter('table'):
				#if element.get('class') == 'news-latest-item':
				txt=[]
				#print len(element), element
				meta = element[7].getchildren()
				for i in range(2,len(meta)-1): # -1 todo
					name = meta[i][1][0][0].text #element[7][2][1][0][0].text
					image  = meta[i][2][0][0].attrib.get('src') #element[7][2][2][0][0].attrib['src']
					url   = meta[i][7][0].attrib.get('href') #element[7][2][7][0].attrib['href']
					entry = [name,image,url]
					out.append(entry)
			return out

		def on_success_head(req,result):
			#print "headers ", req.resp_headers['content-length']
			
			try:
				online_file_size=req.resp_headers['content-length']

				url=req.url
				#url=url.replace(' ','_')
				local_file_size=os.stat(FILE_DOWNLOAD_PATH + url.split('/')[-1]).st_size
				#print 'online_file_size', int(online_file_size)
				#print 'local_file_size ', int(local_file_size)
				
				if int(local_file_size) == int(online_file_size):
					#same, do nothing
					pass
				else:
					#different sizes, get new file
					req.widget.update("image-loading.gif")
					print "------------------------------------..."
					root.reqcntr=MyUrlRequest(\
						url,\
						timeout = 20,\
						on_success = on_success_pdf,\
						on_progress = on_progress2,\
						on_error = on_error2,\
						widget=req.widget)
			
			except:
				pass



		def on_progress2(req, cur_sz, tot_sz):
			
			#print "headers ", req.resp_headers
			#print "status ", req.resp_status
			
			#print tot_sz
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success2(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			
			#print req.resp_status
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
			#image=MyImage(source="b/"+url.split('/')[-1])
				req.widget.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				req.widget.update("fail.png")

		def on_success_pdf(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			
			#print req.resp_status
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
			#image=MyImage(source="b/"+url.split('/')[-1])
				req.widget.update('done.png')
				try:
					if req.head:
						req.head.unbind(on_press=req.head._getpdf)
						req.head.bind(on_press=lambda widget, items=str(url.split('/')[-1]): openpdf(items))
				except:
					pass
					
			else:
				req.widget.update("fail.png")

		def on_error2(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			req.widget.update("fail.png")

		def on_error_head(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			pass

		def openpdf(url):
			save_info("file-"+url)
			from jnius import cast
			from jnius import autoclass
			#pdf="/storage/sdcard0/download/" +url
			# import the needed Java class
			url=url.replace(' ','_')
			url="file://" + FILE_DOWNLOAD_PATH + url
			#print "normalized ", url
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			Uri = autoclass('android.net.Uri')

			# create the intent
			intent = Intent()
			intent.setAction(Intent.ACTION_VIEW)
			target=Uri.parse(url)
			intent.setDataAndType(target, "application/pdf")

			# PythonActivity.mActivity is the instance of the current Activity
			# BUT, startActivity is a method from the Activity class, not our
			# PythonActivity.
			# We need to cast our class into an activity, and use it
			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)



		
		if root.small_screen=="0":
			root.display_catalog_cols=2
		else:
			root.display_catalog_cols=1
			

		
		scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)

		top=GridLayout(cols=1, spacing=0, size_hint_y=None)
		top.bind(minimum_height=top.setter('height'))
		content=GridLayout(cols=root.display_catalog_cols, spacing=0, size_hint_y=None)
		content.bind(minimum_height=content.setter('height'))
		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wit.add_widget(topimg)

		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wib.add_widget(botimg)
		
		top.add_widget(wit)
		top.add_widget(content)
		contentins=GridLayout(cols=root.display_catalog_cols, spacing=0, size_hint_y=None)
		contentins.bind(minimum_height=contentins.setter('height'))
		content.add_widget(contentins)

		
		top.add_widget(wib)
		
		scroll.add_widget(top)
		
		def presss(scroll,where):
			if where < 0.000:
			#wit.size=(Window.width,0)
				#print where
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				#print where
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)
		
		catalogs.add_widget(scroll)
		root.must_create_catalogs=0
		wida=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imageweb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		wida.add_widget(imageweb)
		contentins.add_widget(wida)
	 
		def go(args):
			contentins.remove_widget(wida)

			items=parsecatalogfile()
			items.reverse()
		
		
			for i in items:
				#print i
				btntext="\n\n\n\n\n\n%s" % (i[0])

				btn=ButtonMenu(background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},halign='center',text_size=(Window.width/2-10, None),markup=True)
				
				btn.text=btntext

				image=MyImage(source='image-loading.gif', background_color=coloroverlay, allow_stretch=False, size_hint=(1, 1),pos_hint={'x':-.1, 'y':.2})

				#print items['smlImageUri']
				url="http://robe.cz/"+ i[1]
				url=url.replace(' ','_')
				if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
					image.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				else:
				#p=self.q.push([url, "b/"+url.split('/')[-1]])
					#print imagetop
					#try:
						self.reqcntr=MyUrlRequest(\
							url,\
							timeout = 10,\
							on_success = on_success2,\
							on_progress = on_progress2,\
							on_error = on_error2,\
							widget=image)
					#except:
					#	pass


				statusimage=MyImage(source='image-loading.gif', background_color=coloroverlay, allow_stretch=False, size_hint=(.3, .3),pos_hint={'x':.5, 'y':.55})

				#print items['smlImageUri']
				url="http://robe.cz/"+ i[2]

				if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
					statusimage.update('done.png')
					url=url.replace(' ','_')
					btn.bind(on_press=lambda widget, items=str(url.split('/')[-1]): openpdf(items))


					if root.check_new_manuals=="0":
						pass
					else:
						#do checking here
						
						try:
							req=MyUrlRequest(\
								url,\
								timeout = 10,\
								on_success = on_success_head,\
								on_progress = on_progress2,\
								on_error = on_error_head,\
								method='HEAD',\
								widget=statusimage)
						except:
							pass
						

				else:
					statusimage.update('get.png')
					#print "must download", 
					#print btnimage
					
					def getpdf(args):
						url=args[0]
						widget=args[1]
						btn=args[2]
						#if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
						#	#workaround for not being able to unbind getpdf
						#	pass
						#else:
						try:
							self.reqcntr=MyUrlRequest2(\
							url,\
							timeout = 20,\
							on_success = on_success_pdf,\
							on_progress = on_progress2,\
							on_error = on_error2,\
							widget=widget,\
							head=btn
							)
							widget.update('image-loading.gif')
						except:
							pass

					btn._getpdf=lambda widget, items=(str(url),statusimage,btn): getpdf(items)
					btn.bind(on_press=btn._getpdf)
					
						
					#print root, root.reqcntr
					#reqcntr+=1






				
				wid=FloatLayout(size_hint_y=None, size=(Window.width,180), background_color=coloroverlay)
				
				wid.add_widget(btn)
				#wid.add_widget(lbl)
				
				wid.add_widget(image)
				wid.add_widget(statusimage)
				

				contentins.add_widget(wid)
			
		Clock.schedule_once(partial(go), .8)


	def go_to_topmenu(self,button):
		sm.current='main'
	
	
	def opennews(self,index):
		
		save_info("menu-news")

		#sm.current='article'
		article_dict={}
		
		#carousel = Carousel(direction='right')
		
		#a.reverse()
		def _set_text_height(instance, size):
			#print "_set_summary_height", size
			instance.height = size[1]
		
		#print index
		#print adding_items
		
		def add_article_page(items, kam=0):
			#print "kam ",kam
			#items=a[adding_items[i]]

			
			scroller= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=500,scroll_distance=3, bar_width=0)

			totalmax=WhiteCanvas(cols=1, spacing=0, size_hint_y=None)
			totalmax.bind(minimum_height=totalmax.setter('height'))

			x=items[3]
			x = [s.replace('\r', '') for s in x]
			x = [s.replace('\n', '') for s in x]
			x = [s.replace('\t', '') for s in x]
			
			article_text="%s" % ('\n\n'.join(x))
			article_text="%s" % (article_text)
			from lxml import html
			doc=html.document_fromstring(article_text)
			article_text = doc.text_content()
			
			src=items[2].split('/')[-1]
			if src=='logo.png':
				src='1.jpg'
			else:
				src=TEMP_DOWNLOAD_PATH+items[2].split('/')[-1]


			#title_text="[b]%s[/b]" % (items[0])
			title_text="%s" % (items[0])
			article_title=MyLabelLargeText(text="[color=0000ff]"+title_text+"[/color]", markup=True, haligh='center',size_hint_y=None, text_size=(Window.width-20, None))
		

			
			#articleimage=ArticleImage(source=src,size_hint_y=None,allow_stretch=True)
			#articleimage=ButtonOptionYT(size_hint_y=None,background_normal=src,background_down=src,size=(Window.width-20,Window.width * 0.5 ),allow_stretch=False)
			articleimage=ArticleImage(size_hint_y=None,source=src,size=(Window.width-20,Window.width * 0.4 ),allow_stretch=True,keep_ratio=True,color=(1,1,1,1))
			
			articleimage.bind(on_press=lambda widget, itemsp=items[2].split('/')[-1]: openpicture(itemsp))
			
			
			
			#title_label=MyLabelWithBackground(text='', markup=True, halign='left',size_hint_y=None,text_size=(Window.width-20, None),font_size=50)
			article_label=MyLabelWithBackground(text='', markup=True, halign='left',size_hint_y=None,text_size=(Window.width-20, None),color=(0,0,0,1))
			
			
			#article_label = Label(text="", size_hint_y=None)
			article_label.bind(texture_size=_set_text_height)
			#ppppp
			
			def fill_text(widget):
				
				#article_label.text="[color=0000ff]\n\n"+article_text+"\n[/color]"
				#article_label.text="\n\n"+article_text+"\n"
				tady="%s" % ('\n\n'.join(x))
				article_label.text="[color=0000ff]\n\n"+tady+"\n[/color]"
				
				
			
			Clock.schedule_once(partial(fill_text), 0.77)
			
			#article_label.text=article_text
			
			
			###content.add_widget(article_label)
			
			#content_btn = BoxLayout(orientation='horizontal',spacing=0, size_hint=(1,1))
			
			btn=Button(text="Open in browser",size_hint_y=None,height=50,background_color=coloroverlay)
			btn.bind(on_press=lambda widget, itemsp=items[1]: openweb(itemsp))
			btn.bind(on_press=lambda widget, items="menu-openbrowsernews": save_info(items))			
			
			btnshare=Button(text='Share link…',size_hint_y=None,size_hint_x=.2,height=50,background_color=coloroverlay)#background_normal='share.png'
			btnshare.bind(on_press=lambda widget, itemsp=[items[0],items[1]]: openshare(itemsp))
			btnshare.bind(on_press=lambda widget, items="menu-sharelinknews": save_info(items))			


			btn_2=Button(text="Open in browser",size_hint_y=None,height=100,background_color=coloroverlay)
			#content.add_widget(btn_pdf)
			btn_2.bind(on_press=lambda widget, itemsp=items[1]: openweb(itemsp))
			btn_2.bind(on_press=lambda widget, items="menu-openbrowsernews": save_info(items))			
			
			wit=BoxLayout(size_hint_y=None, size=(Window.width,0))
			topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
			wit.add_widget(topimg)

			wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
			botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
			wib.add_widget(botimg)

			#	layout = Article_display(valigh='top')
			#plusbtn=Button(size_hint=(.14,None),background_normal='glass.png',background_down='glass.png',allow_stretch=False)
			
			#from kivy.factory import Factory
			#Factory.register('Article_display', cls=articleimage)


			#article_label.bind(is_double_tap=plusfont)
			
			
			#articleimage.bind(minusfont=mfont)
			
			#layout.add_widget(plusbtn)
			#layout.add_widget(btn_2)
			
			
			totalmax.add_widget(wit)
			top_content = WhiteCanvas2(orientation='horizontal', size_hint_y=None, height=50, color=[1,0,0,1])

			
			top_content.add_widget(btn)
			top_content.add_widget(btnshare)

			totalmax.add_widget(top_content)
						
			totalmax.add_widget(article_title)
			
			totalmax.add_widget(articleimage)	
			#totalmax.add_widget(layout)	

			
			
			totalmax.add_widget(article_label)
			
			totalmax.add_widget(btn_2)
			
			totalmax.add_widget(wib)

			scroller.add_widget(totalmax)
			article.add_widget(scroller)


			def presss(scroll,where):
				if where < 0.000:
				#wit.size=(Window.width,0)
					#print where,scroll.bar_width
					wib.size=(Window.width,20)
					anim = Animation(size=(Window.width, 0))
					anim.start(wib)
									
					#wit.size=(Window.width,20)
				elif where > 1.000:
					#print where,scroll.bar_width
					wit.size=(Window.width,20)
					anim = Animation(size=(Window.width, 0))
					anim.start(wit)
					
			scroller.bind(scroll_y = presss)




			
			#carousel.add_widget(scroller, index=kam)
			#print "poradi,index ", len(carousel.slides), adding_items[i]
			#print article_dict

		a=self.parserssfile()
		
		article.content.clear_widgets()

		
		#if index==0:
			#adding_items=[0,1]
			#select=0
		#elif index==len(a)-1:
			#adding_items=[ len(a)-1, len(a)-2]
			#select=1
		#else:
			#adding_items=[index-1,index,index +1]
			#select=1

		#a.reverse()
		
		#for i in (range(len(a))):
		#for i in (range(len(adding_items))):
			#print i, adding_items[i]
			#items=a[adding_items[i]]
		items=a[index]
		add_article_page(items,kam=0)
			#article_dict[len(carousel.slides)]=adding_items[i]
			
		def ktery(widget, slide):
			pass
			#print "pozice ", slide
			#print "aktualni index", article_dict[slide+1]
			#print "children ",carousel.children
			#print widget, slide
			#print carousel.current_slide
			#print carousel.current_slide.article_label
			
			#if slide==0:
				#print "nula"
				#print "pridat ", article_dict[slide+1]-1
				#carousel.remove_widget(carousel.next_slide)
				#add_article_page(items=a[article_dict[slide+1]-1],kam=2)
				#article_dict[len(carousel.slides)]=article_dict[slide+1]
				
				##items=a[adding_items[article_dict[slide+1]]]

			#elif slide==2:
				#print "dvojka"
				#print "pridat ", article_dict[slide+1]+1
				##print "-----", len(carousel.slides)
				##carousel.remove_widget(carousel.previous_slide)
				#add_article_page(items=a[article_dict[slide+1]+1],kam=2)
				#article_dict[len(carousel.slides)]=article_dict[slide+1]-1
				
				
				
				
			#print slide
			#print adding_items
			#print article_dict[slide+1]
		#xxxx=['bbb']
		#carousel.bind(index=lambda widget, items=article_label:ktery(items))
		#carousel.bind(index=ktery)
		

		#print "set car", 10-index, index	
		#carousel.index=index
		#article.add_widget(scroll)
		#article.add_widget(scroll)
		
		def openweb(url):
			url="http://robe.cz/"+url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)
			import webbrowser
			webbrowser.open(url) 

		
		def openshare(items):
			#save_info("menu-sharenews")
			url="http://robe.cz/"+items[1]
			try:
				#pass
				subject=items[0]
			except:
				pass
			#subject=items[0]

			from jnius import cast
			from jnius import autoclass
			
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			intent = Intent()
			intent.setType("text/plain");
			intent.setAction(Intent.ACTION_SEND)
			
			#intent.putExtra(Intent.EXTRA_SUBJECT, "Check this out" + subject)
			try:
				#pass	
				intent.putExtra(Intent.EXTRA_SUBJECT, "Check this out: " + subject)
			except:
				pass
			intent.putExtra(Intent.EXTRA_TEXT, url)
			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)

		def openpicture(src):
			src="file://" + FILE_DOWNLOAD_PATH + src
			
			#print src

			from jnius import cast
			from jnius import autoclass
			
		
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			Uri = autoclass('android.net.Uri')
			intent = Intent()
			
			intent.setAction(Intent.ACTION_VIEW)
			
			target=Uri.parse(src)
			intent.setDataAndType(target, "image/jpeg")

			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)
		
		sm.current='article'
			 
		


	def parserssfile(self):
		out=[]
		feed = open("rss.txt", mode="r")
		feed = etree.parse(feed,etree.HTMLParser())
		feed = feed.getroot()
		
		def stringify_children(node):
			from lxml.etree import tostring
			from itertools import chain
			parts = ([node.text] + list(chain(*([c.text, tostring(c), c.tail] for c in node.getchildren()))) + [node.tail])
			# filter removes possible Nones in texts and tails
			return '\n'.join(filter(None, parts)).replace('\t',' ')
			
    
    
		for element in feed.iter('div'):
			if element.get('class') == 'news-latest-item':
				txt=[]
				#print len(element), element
				meta = element.getchildren()
				#print meta
				#for tags in meta:
				title = meta[0][0].attrib.get('title','')
				
				link = meta[0][0].attrib.get('href',DEFAULT_LINK)
				#img =  meta[1].attrib['src']
				img =  meta[1].attrib.get('src','logo.png')
				#print title, link, img
				#print "- - - - - - - - - - - - - - "
				for paragraph in element.findall('p'):
					#if paragraph is None:
						#print paragraph
					ttt=stringify_children(paragraph)
					#print ttt
					txt.append(ttt)
					#txt.append(paragraph.text)
					#print paragraph.text
					#print "--------------------",paragraph.text
				#if not txt : txt.append('...')
				#print txt
				#print "- - - - - - - - - - - - - - "
				entry = [title,link,img,txt]
				#print entry
				out.append(entry)
		return out

	def parseytfile(self):
		out=[]
		feed = open("yt.txt", mode="r")
		feed = etree.parse(feed,etree.HTMLParser())
		feed = feed.getroot()
		
    
		for element in feed.iter('entry'):
				txt=[]
				meta = element.getchildren()
				title=meta[5].text
				link=meta[7].attrib['href']
				entry = [title,link]
				
				out.append(entry)
		return out


	def parsefbfile(self):
		out=[]
		fa = open("fbfeed.txt", mode="r")
		a=fa.read()
		fb = open("fbposts.txt", mode="r")
		b=fb.read()
		
		
		import json
		alla=json.loads(a)
		
		allb=json.loads(b)
		
		all1=alla['data']
		all2=allb['data']
		
		all=all1+all2
		
		#all=all1 + list(set(all2) - set(all1))
		
		
		#all=all1

		#all1.update(all2)
		
		
		#print all

		#print len(all)
		for i in all:
			entry=[]
			title=''
			link='http://www.facebook.com/127423910605493/'
			post_type=''
			likes='0'
			comments='0'
			picture='logo.png'
			message=''
			timestamp=''
			try:
				if i.get('type'):
					post_type=i['type']
					#print post_type
				
				if post_type=='status' or post_type=='photo': 
					if i.get('message'):
						message=i['message']
						#print "msg: ",message
					else:
						if i.get('story'):
							message=i['story']
							#print "msg: ",message
					
					##if i.get('from'):
					##	link='http://www.facebook.com/'+i['from']['id']
					##	print link
				
						
					
				if i.get('created_time'):
					timestamp=i['created_time']
	
					
				if i.get('name'):
					title=i['name']
					#print title
				
				if i.get('link'):
					link=i['link']
					#print link

				if i.get('likes'):
					likes=i['likes']['count']
					#print likes
				if i.get('comments'):
					comments=i['comments']['count']
					#print comments
				if i.get('picture'):
					picture=i['picture']
					#print picture
					
					#description=meta[3].text
				entry = [title.replace('\r',''),link, post_type,likes,comments,picture,message.replace('\r',''),timestamp]
				#print entry
					#print entry
				if entry in out:
					pass
					#print "dupl", entry
				else:
					out.append(entry)
			except:
			#	print i
				pass
		from operator import itemgetter	
		out.sort(key=itemgetter(7),reverse=True)
		return out

	def parsefbfileorig(self):
		out=[]
		feed = open("fb.txt", mode="r")
		feed = etree.parse(feed,etree.XMLParser())

		feed = feed.getroot()


		for element in feed.iter('item'):
			entry=[]
			meta = element.getchildren()
			title=meta[1].text
			link=meta[2].text
			#description=meta[3].text
			entry = [title,link]
			out.append(entry)
		
		return out



	def store_rss(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('rss.txt').st_size)
			f = open('rss.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('rss.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				self.CreateNews()

	def store_cal(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('cal.txt').st_size)
			f = open('cal.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('cal.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				self.CreateCalendar()
			#self.create()

	def store_gobos(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			f = open('gobos.txt','w')
			f.write(str(result))
			f.close()
			#self.create()

	def store_catalogs(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('catalogs.txt').st_size)
			f = open('catalogs.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('catalogs.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				self.CreateCatalogs()
			#self.create()

	def store_yt(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('yt.txt').st_size)
			f = open('yt.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('yt.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				self.CreateNews()

	def store_fb_feed(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('fbfeed.txt').st_size)
			f = open('fbfeed.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('fbfeed.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				#print self.parsefbfile()
				root.mynews.CreateFB()
				#pass
			#print self.parsefbfile()
	
	def store_fb_posts(self,req, result):
		#print "got data"
		
		if len(result) > 0 and req.resp_status ==200:
			old_file_size=int(os.stat('fbposts.txt').st_size)
			f = open('fbposts.txt','w')
			f.write(str(result))
			f.close()
			new_file_size=int(os.stat('fbposts.txt').st_size)
			#print old_file_size, old_file_size
			if int(old_file_size) != int(new_file_size):
				#print self.parsefbfile()
				root.mynews.CreateFB()
				#pass
			#print self.parsefbfile()

	def store_fb_token(self,req, result):
		#print "got data"
		#http://stackoverflow.com/questions/6214535/what-is-the-difference-between-feed-posts-and-statuses-in-facebook-graph-api
		
		#print result
		if len(result) > 0 and req.resp_status ==200:
			
			token=result
			#print token
			url="https://graph.facebook.com/127423910605493/feed?%s" % (token) #feed, posts
			#print url
			try:
				self.fb_get=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_fb_feed,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss)			

				url="https://graph.facebook.com/127423910605493/posts?%s" % (token) #feed, posts
				#print url
				self.fb_get=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_fb_posts,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss)			
					
			except:
				pass



	def on_progress_rss(self,req, cur_sz, tot_sz):
		#print req, cur_sz, tot_sz
		Clock.schedule_once(partial(self.update_progress, req, cur_sz, tot_sz), 1)
		pass
		
	def update_progress(*args):
		pass
	def on_error_rss(self,req, err):
		pass
		#print 'error on_request:', req, err

	def getrssfile(self, *args):
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://robe.cz/index.php?id=927'
		
		try:
			self.rss=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_rss,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss
					)
		except:
			pass

	def getfbfile(self, *args):
		
		#get token:
		
		#print "getting fb file"
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		#url='http://www.facebook.com/feeds/page.php?format=rss20&id=127423910605493'
		FB_ID="XXXXXXXX"
		FB_SECRET="XXXXXXXX"

		url="https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=%s&client_secret=%s" % (FB_ID, FB_SECRET)

		
		#headers = {'User-agent':'Mozilla/5.0'}
		try:
			self.fb=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_fb_token,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss
					)
		except:
			pass
		#print self.fb
		
	def getfbfileorig(self, *args):
		#print "getting fb file"
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://www.facebook.com/feeds/page.php?format=rss20&id=127423910605493'
		headers = {'User-agent':'Mozilla/5.0'}
		try:
			self.fb=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_fb,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss,
					req_headers=headers
					)
		except:
			pass


	def getcalfile(self,*args):
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://www.robe.cz/exhibitions/'
		try:

			self.cal=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_cal,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss
					)
		except:
			pass
	def getgobosfile(self,*args):
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://www.robe.cz/fileadmin/robe/downloads/dmx_charts/gobo_images/'

		self.gobos=UrlRequest(url,\
				timeout = 15,\
				on_success = self.store_gobos,\
				on_progress = self.on_progress_rss,\
				on_error = self.on_error_rss
				)

	def getcatalogsfile(self,*args):
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://www.robe.cz/support/file-cat/catalogues/'
		try:
			self.catalogs=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_catalogs,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss
					)
		except:
			pass


	def getytfile(self,*args):
		#url='http://www.root.cz/rss/clanky'
		#url='http://www.robe.cz/index.php?id=201&type=100'
		url='http://gdata.youtube.com/feeds/api/users/RobeLightingTube/uploads'
		try:
			self.yt=UrlRequest(url,\
					timeout = 15,\
					on_success = self.store_yt,\
					on_progress = self.on_progress_rss,\
					on_error = self.on_error_rss
					)

		except:
			pass


	def update():
		self.getrssfile()
		
		pass			
				
	
	def CreateNewsHorizontal(self,text=None):
		#print "HORIZONTAL"
		def on_success_image(req, result):
			#print "got data", req.url , req.url.split('/')[-1]
		
			fle=TEMP_DOWNLOAD_PATH+req.url.split('/')[-1]
			#fle=fle.replace(' ','_')
			#print fle
		
			if len(result) > 0 and req.resp_status ==200:
				f = open(fle,'w')
				f.write(str(result))
				f.close()
				
				req.widget.update(fle)

		def on_progress_image(req, cur_sz, tot_sz):
			#print req, cur_sz, tot_sz
			Clock.schedule_once(partial(update_progress_image, req, cur_sz, tot_sz), 1)
			pass
			
		def update_progress_image(*args):
			pass
			
		def on_error_image(req, err):
			pass
			#print 'error on_request:', req


		def openweb(url):
			url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)
			import webbrowser
			webbrowser.open(url) 


		
		
		self.clear_widgets()
		#print "BUILDING"
		
		#display_minus_videos
		#root.display_rows
		
		totalmax=WhiteCanvas(rows=1, spacing=0, size_hint_x=None, color=(1,0,1,1))
		totalmax.bind(minimum_width=totalmax.setter('width'))
		
		if root.small_screen=="0":
				root.display_rows=3
		else:
				root.display_rows=1

		
		total=GridLayout(rows=root.display_rows, spacing=8, size_hint_x=None)
		
		total.bind(minimum_width=total.setter('width'))
		
		layout = GridLayout(rows=1, spacing=8, size_hint_x=None)
		layout.bind(minimum_width=layout.setter('width'))
		
		layout2 = GridLayout(rows=1, spacing=8, size_hint_x=None)
		layout2.bind(minimum_width=layout2.setter('width'))
		
		layout3 = GridLayout(rows=1, spacing=8, size_hint_x=None, size_hint=(None,.3))
		layout3.bind(minimum_width=layout3.setter('width'))

		#widcal=BoxLayout(orientation='vertical', size_hint_x=None, width=216)
		#doccal = ButtonOption(desc='[color=000000]Exhibition\ncalendar[/color]', background_normal='calendar.jpg',background_down='logo.png',allow_stretch=False)
		
		#doccal.bind(on_press=self.display_calendar)
		
		#widcal.add_widget(doccal)
		#layout.add_widget(widcal)


		#widbro=BoxLayout(orientation='vertical', size_hint_x=None, width=216)
		#docbro = ButtonOption(desc='[color=000000]Product\nbrochures[/color]', #background_normal='brochures.jpg',background_down='logo.png',allow_stretch=False)
		#docbro.bind(on_press=self.display_catalogs)
		
		#widbro.add_widget(docbro)
		#layout.add_widget(widbro)


		#wid2=BoxLayout(orientation='vertical', size_hint_x=None, width=200)
		#doc2 = ButtonOption(text='[b]Website[/b]', markup=True, color=(1,1,1,1),background_color=imageoverlay,background_normal='website.png',background_down='logo.png',allow_stretch=False)
		#doc2.bind(on_press=lambda widget, items='http://www.robe.cz': openweb(items))
		#wid2.add_widget(doc2)
		#layout.add_widget(wid2)

		
		vidwid=BoxLayout(orientation='vertical', size_hint_x=None,width=216,heigth=20)
		viddoc = ButtonOptionYT(text='YouTube\nChannel:', markup=True,color=(1,.7,1,1),background_color=(.5,.7,1,1),background_normal='yt.png',allow_stretch=False)
		viddoc.bind(on_press=lambda widget, items='http://www.youtube.com/user/RobeLightingTube': openweb(items))
		viddoc.bind(on_press=lambda widget, items="menu-openytchannel": save_info(items))
		
		vidwid.add_widget(viddoc)
		layout3.add_widget(vidwid)


		#youtube
		vid=self.parseytfile()
		vid.reverse()
		vidwidth=216
		for i in range(0,len(vid)-7):#-7
			vidtitle,vidurl=vid.pop()
			vidtitle="%s" % ("\n".join(wrap(vidtitle.replace('ROBE lighting - ','').replace('ROBE lighting',''),17)))
			vidwid=BoxLayout(orientation='vertical', size_hint_x=None,width=vidwidth)
			viddoc = ButtonOptionYT(text=vidtitle, color=(1,.7,1,1),background_color=(.5,.7,1,1),background_normal='yt.png')
			viddoc.bind(on_press=lambda widget, items=vidurl: openweb(items))
			viddoc.bind(on_press=lambda widget, items="menu-openytmovie": save_info(items))
			vidwid.add_widget(viddoc)
			layout3.add_widget(vidwid)
		

		
		
		a=self.parserssfile()
		#print a


		a.reverse()
		#print "ITEMS: ", len(a)
		
		
		amount=len(a)-1
	
		
		for i in range(0,amount,2):
			width=440
			width2=440
			wwlen=37
			wwlen2=37
			if (i == 0):
				width2=216 
				wwlen2=18
			
			if  (i == 18):
				width=216 
				wwlen=18

				
			
				
			#title, link, img, text
			x,y,z,zz=a.pop()
			y="http://robe.cz/"+y
			z="http://robe.cz/"+z

			
			all1=x,y,z,zz
			
			if len(x)>wwlen*2-7:
				x=x[0:wwlen*2-7]+u'…'
			
			x="[color=000000]%s[/color]" % ("\n".join(wrap(x,wwlen)))
			#x="[color=000000][b]%s[/b][/color]" % x
			
			
			#img1=str(i+5)
			#img2=str(i)
			wid=BoxLayout(orientation='vertical', size_hint_x=None, width=width)
			doc = ButtonOption(desc=x, background_normal='1.jpg',background_down='logo.png',allow_stretch=False)
			doc.bind(on_press=lambda widget, items=i: self.opennews(items))
			wid.add_widget(doc)
			if root.small_screen=="1":
				layout.add_widget(wid)
			else:
				layout2.add_widget(wid)


			url=z
			url=url.replace(' ','_')
			#print url
			if url.split('/')[-1]=='logo.png':
				doc.update('1.jpg')
			
			elif os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
				doc.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])

			else:
				try:
					root.img1=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success_image,\
						on_progress = on_progress_image,\
						on_error = on_error_image,\
						widget=doc)
				except:
					pass
			
			
			
			
			x,y,z,zz=a.pop()
			y="http://robe.cz/"+y
			z="http://robe.cz/"+z
			all2=x,y,z,zz
			url=z
			#print url
			if len(x)>wwlen2*2-7:
				x=x[0:wwlen2*2-7]+u'…'
			x="[color=000000]%s[/color]" % ("\n".join(wrap(x,wwlen2)))
			#x="[color=000000][b]%s[/b][/color]" % x
			
			
			wid2=BoxLayout(orientation='vertical', size_hint_x=None, width=width2)
			doc2 = ButtonOption(desc=x, background_normal='0.jpg',background_down='logo.png',allow_stretch=False)
			doc2.bind(on_press=lambda widget, items=i +1: self.opennews(items))
			wid2.add_widget(doc2)
			layout.add_widget(wid2) #layout2

			url=z
			
			if url.split('/')[-1]=='logo.png':
				doc.update('1.jpg')

			elif os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
				doc2.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				try:
					root.img2=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success_image,\
						on_progress = on_progress_image,\
						on_error = on_error_image,\
						widget=doc2)
				except:
					pass



		
		total.add_widget(layout)
		total.add_widget(layout2)
		total.add_widget(layout3)
		


		wil=FloatLayout(size_hint_x=None,width=0, size=(8,0))
		limg=Image(color=[0,0,0,0],size_hint_x=None,width=0)
		wil.add_widget(limg)

		wir=FloatLayout(size_hint_x=None,width=0,size=(8,0))
		rimg=Image(color=[0,0,0,0],size_hint_x=None,width=0)
		wir.add_widget(rimg)
		
		totalmax.add_widget(wil)
		totalmax.add_widget(total)
		
		totalmax.add_widget(wir)
		
		scroll= ScrollView(size_hint=(1, 1), scroll_timeout=255, scroll_distance=20,bar_width=0)#xxxxx

		def presss(scroll,where):
			#print where
			if where < 0.000:
				#print where
				wil.size=(20,0)
				anim = Animation(size=(8, 0))
				
				anim.start(wil)
				
			elif where > 1.000:
				#print where
				wir.size=(20,0)
				anim = Animation(size=(8, 0))
				
				anim.start(wir)
				
		scroll.bind(scroll_x = presss)


		
		scroll.add_widget(totalmax)
		
		
		self.add_widget(scroll)
	

	def CreateNewsVertical(self,text=None):
		#print "VERTICAL"
		def on_success_image(req, result):
			#print "got data", req.url , req.url.split('/')[-1]
		
			fle=TEMP_DOWNLOAD_PATH+req.url.split('/')[-1]
			#fle=fle.replace(' ','_')
			#print fle
		
			if len(result) > 0 and req.resp_status ==200:
				f = open(fle,'w')
				f.write(str(result))
				f.close()
				
				req.widget.update(fle)

		def on_progress_image(req, cur_sz, tot_sz):
			#print req, cur_sz, tot_sz
			Clock.schedule_once(partial(update_progress_image, req, cur_sz, tot_sz), 1)
			pass
			
		def update_progress_image(*args):
			pass
			
		def on_error_image(req, err):
			#print 'error on_request:', req
			pass


		def openweb(url):
			url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)
			
			import webbrowser
			webbrowser.open(url) 


		
		
		self.clear_widgets()
		#print "BUILDINGvertival"
		
		totalmax=WhiteCanvas(cols=1, spacing=0, size_hint_y=None, color=(1,0,1,1))
		totalmax.bind(minimum_height=totalmax.setter('height'))
		
		
		#display_minus_videos
		#root.display_rows
		
		if root.small_screen=="0":
			root.display_rows=5	#5
		else:
			root.display_rows=1	#5

		total=GridLayout(cols=root.display_rows, spacing=8, size_hint_y=None)#5
		total.bind(minimum_height=total.setter('height'))
		
		layout = GridLayout(cols=1, spacing=8, size_hint_y=None)
		layout.bind(minimum_height=layout.setter('height'))
		
		layout2 = GridLayout(cols=1, spacing=8, size_hint_y=None)
		layout2.bind(minimum_height=layout2.setter('height'))
		
		layout3 = GridLayout(cols=1, spacing=8, size_hint_y=None, size_hint=(.3,None))
		layout3.bind(minimum_height=layout3.setter('height'))
		

		

		#widcal=BoxLayout(orientation='horizontal', size_hint_y=None, height=216)#216
		#doccal = ButtonOption(desc='[color=000000]Exhibition\ncalendar[/color]', background_normal='calendar.jpg',background_down='logo.png',allow_stretch=False)
		
		
		#doccal.bind(on_press=self.display_calendar)
		#widcal.add_widget(doccal)
		
		#layout.add_widget(widcal)

		
		#widbro=BoxLayout(orientation='horizontal', size_hint_y=None, height=216) #216
		#docbro = ButtonOption(desc='[color=000000]Product\nbrochures[/color]', background_normal='brochures.jpg',background_down='logo.png',allow_stretch=False)
		#xxxx
		
		#docbro.bind(on_press=self.display_catalogs)
		#widbro.add_widget(docbro)
		
		#if root.small_screen=="1":
		#	layout.add_widget(widbro)
		#else:
		#	layout2.add_widget(widbro)


		#wid2=BoxLayout(orientation='vertical', size_hint_x=None, width=200)
		#doc2 = ButtonOption(text='[b]Website[/b]', markup=True, color=(1,1,1,1),background_color=imageoverlay,background_normal='website.png',background_down='logo.png',allow_stretch=False)
		#doc2.bind(on_press=lambda widget, items='http://www.robe.cz': openweb(items))
		#wid2.add_widget(doc2)
		#layout.add_widget(wid2)

		
		vidwid=BoxLayout(orientation='horizontal', size_hint_y=None,height=142)
		viddoc = ButtonOptionYT(text='YouTube\nChannel:',color=(1,.7,1,1),background_color=(.5,.7,1,1),background_normal='yt.png')
		viddoc.bind(on_press=lambda widget, items='http://www.youtube.com/user/RobeLightingTube': openweb(items))
		vidwid.add_widget(viddoc)
		layout3.add_widget(vidwid)


		#youtube
		vid=self.parseytfile()
		vid.reverse()
		vidwidth=141
		for i in range(0,len(vid)-11): #10
			vidtitle,vidurl=vid.pop()
			vidtitle=vidtitle.replace('ROBE lighting -','').replace('ROBE lighting','')
			#vidtitle=vidtitle.replace('ROBE lighting','')
			if len(vidtitle)>35:
				vidtitle=vidtitle[0:15]+u'…'
			vidtitle="%s" % ("\n".join(wrap(vidtitle,8)))
			
			vidwid=BoxLayout(orientation='horizontal', size_hint_y=None,height=vidwidth)
			viddoc = ButtonOptionYT(text=vidtitle, color=(1,.7,1,1),background_color=(.5,.7,1,1),background_normal='yt.png')
			viddoc.bind(on_press=lambda widget, items=vidurl: openweb(items))
			vidwid.add_widget(viddoc)
			layout3.add_widget(vidwid)
		
		#vidwid=BoxLayout(orientation='horizontal', size_hint_y=None,height=71)
		#viddoc = ButtonOptionYT(text='',color=(1,.7,1,1),background_color=(.5,.7,1,1),background_normal='yt.png')
		#vidwid.add_widget(viddoc)
		#layout3.add_widget(vidwid)

		
		
		a=self.parserssfile()
		#print a


		a.reverse()
		#print "ITEMS: ", len(a)
		
		amount=len(a)-1
		
		for i in range(0,amount,2):
			width=216
			wwlen=29
				
			
				
			#title, link, img, text
			x,y,z,zz=a.pop()
			y="http://robe.cz/"+y
			z="http://robe.cz/"+z

			
			all1=x,y,z,zz
			
			if len(x)>wwlen*2-9:
				x=x[0:wwlen*2-9]+u'…'
			
			x="[color=000000]%s[/color]" % ("\n".join(wrap(x,wwlen)))
			#x="[color=000000][b]%s[/b][/color]" % x
			
			
			#img1=str(i+5)
			#img2=str(i)
			wid=BoxLayout(orientation='horizontal', size_hint_y=None, height=width)
			doc = ButtonOption(desc=x, background_normal='1.jpg',background_down='logo.png',allow_stretch=False)
			doc.bind(on_press=lambda widget, items=i: self.opennews(items))
			wid.add_widget(doc)
			
			if root.small_screen=="0":
				layout2.add_widget(wid) #layout
			else:
				layout.add_widget(wid) #layout
			

			url=z
			url=url.replace(' ','_')
			#print url
			
			if url.split('/')[-1]=='logo.png':
				doc.update('1.jpg')

			elif os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
				doc.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				try:
					root.img1=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success_image,\
						on_progress = on_progress_image,\
						on_error = on_error_image,\
						widget=doc)
				except:
					pass
			
			
			
			
			x,y,z,zz=a.pop()
			y="http://robe.cz/"+y
			z="http://robe.cz/"+z
			all2=x,y,z,zz
			url=z

			if len(x)>wwlen*2-9:
					x=x[0:wwlen*2-9]+u'…'
			x="[color=000000]%s[/color]" % ("\n".join(wrap(x,wwlen)))
			#x="[color=000000][b]%s[/b][/color]" % x
			
			
			wid2=BoxLayout(orientation='horizontal', size_hint_y=None, height=width)
			doc2 = ButtonOption(desc=x, background_normal='0.jpg',background_down='logo.png',allow_stretch=False)
			doc2.bind(on_press=lambda widget, items=i +1: self.opennews(items))
			wid2.add_widget(doc2)
			layout.add_widget(wid2) #layout2

			url=z
			
			if url.split('/')[-1]=='logo.png':
				doc.update('1.jpg')
			elif os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
				doc2.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				try:
					root.img2=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success_image,\
						on_progress = on_progress_image,\
						on_error = on_error_image,\
						widget=doc2)
				except:
					pass


		wil=FloatLayout(size_hint_x=None,width=0,size=(0,0))
		limg=Image(color=[0,0,0,0],size_hint_x=None,width=0)
		wil.add_widget(limg)

		wir=FloatLayout(size_hint_x=None,width=0,size=(0,0))
		rimg=Image(color=[0,0,0,0],size_hint_x=None,width=0)
		wir.add_widget(rimg)

		wit=BoxLayout(orientation='horizontal', size_hint_y=None, height=0)
		topimg=Image(size=(0,0),color=[1,1,1,1])
		wit.add_widget(topimg)

		wib=BoxLayout(orientation='horizontal', size_hint_y=None, height=0)
		botimg=Image(size=(0,0),color=[1,1,1,1])
		wib.add_widget(botimg)


		if root.small_screen=="0":
			total.add_widget(wil)
		
		total.add_widget(layout)
		total.add_widget(layout2)
		total.add_widget(layout3)
		
		if root.small_screen=="0":
			total.add_widget(wir)

		totalmax.add_widget(wit)
		totalmax.add_widget(total)
		totalmax.add_widget(wib)
		
		
		scroll= ScrollView(size_hint=(1, 1), scroll_timeout=255, scroll_distance=20,bar_width=0)#xxxxx

		def presss(scroll,where):
			#print where
			if where < 0.000:
				#print where
				wib.size=(0,20)
				anim = Animation(size=(0, 0))
				
				anim.start(wib)
				
			elif where > 1.000:
				#print where
				wit.size=(0,20)
				anim = Animation(size=(0, 0))
				
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)


		
		scroll.add_widget(totalmax)
		
		
		self.add_widget(scroll)
	
	def CreateNews(self):
		#print ".......................", root.autorotate
		if root.autorotate=="0":
			root.mynews.CreateNewsHorizontal()
			#print "HORIZONTAL"
		else:
			root.mynews.CreateNewsVertical()
			#print "VERTICAL"

      

class Norbert(App):
	title = 'Norbert'
	icon = 'icon.png'
	connection = None
	use_kivy_settings = False
	
	#from kivy.factory import Factory
	#Factory.register('MySettings',cls=MySettings)
	#settings=MySettings()
	#ensure non closing on android
	def on_pause(self):
		return True
	
	
		
	def build(self):
		#catch escape (back) key on android
		from kivy.base import EventLoop 
		
		EventLoop.window.bind(on_keyboard=self.hook_keyboard)
		
		conf=ConfigParser()
		conf.read('norbert.ini')
		#config = self.config
		#autorotate=conf.get('usersettings', 'autorotate')
		root.check_new_manuals=conf.get('usersettings', 'check_new_manuals')
		root.autodownload=conf.get('usersettings', 'autodownload')
		root.autorotate=conf.get('usersettings', 'autorotate')
		root.small_screen=conf.get('usersettings', 'small_screen')
		root.rand_uid=conf.get('usersettings', 'uid')
		#print root.rand_uid
		
		if root.autorotate=="1" or root.autorotate==1:
			Window.rotation=90

		root.downloading=0 #initializing variable, here we will store number of active downloads from batch downloader
		
		self.intro()
		self.call_home()
		
		return root
		
		
	def build_config(self, config):   
		#print "###########################################################################"
		config.read('norbert.ini')
		config.adddefaultsection('usersettings')
		config.setdefault('usersettings', 'autodownload', 1)
		config.setdefault('usersettings', 'autorotate', 0)
		config.setdefault('usersettings', 'check_new_manuals', 1)
		config.setdefault('usersettings', 'small_screen', 0)
		rand_uid=os.urandom(32).encode('hex')
		config.setdefault('usersettings', 'uid', rand_uid)
		#config.set('usersettings', 'uid', rand_uid)
		
		config.write()

		


	def change_reported(self, settings, config, section, key, value):
		#print "changing"
		change = (section, key, value)
		#print change, config
		#autorotate=config.get('usersettings', 'autorotate')
		root.check_new_manuals=config.get('usersettings', 'check_new_manuals')
		root.autodownload=config.get('usersettings', 'autodownload')
		root.autorotate=config.get('usersettings', 'autorotate')
		root.small_screen=config.get('usersettings', 'small_screen')
		
		
		#print "...............",autorotate
		#print root.check_new_manuals
		#print root

		if key=='autorotate' or key=='small_screen':
			#must recreate / redraw views on rotation and screen size change

			#mynews=News()

			root.must_create_calendar=1
			root.must_create_catalogs=1
			root.must_create_menu=1
			root.must_create_fb=1


			def rework_menu(widget):
				root.mynews.CreateNews()
				root.wifb.clear_widgets()
				root.mynews.CreateFB()
					
					
			if root.autorotate=="1": 
				Window.rotation=90
				sm.current='topmenu'

				Clock.schedule_once(partial(rework_menu), 0.5)

			if root.autorotate=="0":
				Window.rotation=0
				sm.current='topmenu'
				Clock.schedule_once(partial(rework_menu), 0.5)

				

		
	def build_settings(self,settings):
		

		
		def download_all(self):
			save_info("menu-downloadall")
			pl = plistlib.readPlist('dataWithId')
			
			def on_progress2(req, cur_sz, tot_sz):
				
				Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
				pass
				
			def update_progress(*args):
				pass
			def on_success2(req,result):
				#print "sucess2", req.url
				root.downloading-=1
				item8.desc="...downloading " + str(root.downloading)
				
				if root.downloading<=0:
					downloadimage.update("dot.png")
					item8.desc="might take a long time"
					
				url=req.url
				if len(result) > 0 and req.resp_status ==200:
					f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
					f.write(str(result))
					f.close()
				else:
					pass
					

			def on_success_pdf(req,result):
				#print "sucess pdf", req.url
				root.downloading-=1
				item8.desc="...downloading " + str(root.downloading)
				if root.downloading<=0:
					downloadimage.update("dot.png")
					item8.desc="might take a long time"
					
				url=req.url
				
				if len(result) > 0 and req.resp_status == 200:
					f = open(FILE_DOWNLOAD_PATH + url.split('/')[-1],'w')
					f.write(str(result))
					f.close()
					item4.desc="using " + get_size()+"MB"
					
				else:
					pass


			def on_success_head(req,result):
				#print "sucess head", req.url
				try:
					online_file_size=req.resp_headers['content-length']

					url=req.url
					#url=url.replace(' ','_')
					local_file_size=os.stat(FILE_DOWNLOAD_PATH + url.split('/')[-1]).st_size
					#print 'online_file_size', int(online_file_size)
					#print 'local_file_size ', int(local_file_size)
					
					if int(local_file_size) == int(online_file_size):
						#same, do nothing
						pass
					else:
						#different sizes, get new file
						#print "new file", req.url
						try:
							root.reqcntr=UrlRequest(\
								url,\
								timeout = 20,\
								on_success = on_success_pdf,\
								on_progress = on_progress2,\
								on_error = on_error_btn,\
								)
							root.downloading+=1
							item8.desc="...downloading " + str(root.downloading)
							downloadimage.update("image-loading.gif")
						except:
							pass
				
				except:
					pass
				


			def on_error_head(req, *args):
				#print "download error"
				#print req
				#print 'error on_request:', req
				#print "error head", req.url
				pass
				
				
			def on_error2(req, *args):
				#print "download error"
				#print req
				#print 'error on_request:', req
				#print "error2", req.url
				pass
				root.downloading-=1
				item8.desc="...downloading " + str(root.downloading)
				if root.downloading<=0:
					downloadimage.update("dot.png")
					item8.desc="might take a long time"

			def on_error_btn(req, *args):
				#print "download error"
				#print req
				#print 'error on_request:', req
				#print "error btn", req.url
				pass
				root.downloading-=1
				item8.desc="...downloading " + str(root.downloading)
				if root.downloading<=0:
					downloadimage.update("dot.png")
					item8.desc="might take a long time"

			
			for items_i in pl.values()[0]: #items_i 

				#subproducts=products_i['items']

				for items in items_i['items']:

					url=""
								
					
					for c in items.keys():
						#print items
						#print "c", c
						
						if c=='title':
							pass
							
							#print b[c]['label'],b[c]['url']
						elif c=='smlImageUri':
							
							url="http://robe.cz"+ items['smlImageUri']
							url=url.replace(' ','_')
							#p=self.q.push([url, "b/"+url.split('/')[-1]])
								#print imagetop
							try:
								
								self.reqcntr=UrlRequest(\
									url,\
									timeout = 20,\
									on_success = on_success2,\
									on_progress = on_progress2,\
									on_error = on_error2,\
									)
								root.downloading+=1
								item8.desc="...downloading " + str(root.downloading)
								downloadimage.update("image-loading.gif")
								#img=MyImage(source='')
							except:
								pass
								
							
						elif c.find('button') == 0:

							#print "working on ", str(items[c]['label'])
							url="http://robe.cz"+ items[c]['url']
							url=url.replace(' ','_')
							#print url
							if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
								if root.check_new_manuals=="0":
									pass
								else:
									#do checking here
									try:
										
										root.reqcntr=UrlRequest(\
											url,\
											timeout = 20,\
											on_success = on_success_head,\
											on_progress = on_progress2,\
											on_error = on_error_head,\
											method='HEAD',\
											)
									except:
										pass

							else:
								
								#print "must download", 
								#print btnimage
								try:
									root.reqcntr=UrlRequest(\
										url,\
										timeout = 20,\
										on_success = on_success_pdf,\
										on_progress = on_progress2,\
										on_error = on_error_btn,\
										)
										
									#print root, root.reqcntr
									root.downloading+=1
									item8.desc="...downloading " + str(root.downloading)
									downloadimage.update("image-loading.gif")
									
								except:
									pass

			#-------------------------------
			def parsecatalogfile():
				from lxml import etree
				out=[]
				feed = open("catalogs.txt", mode="r")
				feed = etree.parse(feed,etree.HTMLParser())
				feed = feed.getroot()


				for element in feed.iter('table'):
					#if element.get('class') == 'news-latest-item':
					txt=[]
					#print len(element), element
					meta = element[7].getchildren()
					for i in range(2,len(meta)-1): # -1 todo
						name = meta[i][1][0][0].text #element[7][2][1][0][0].text
						image  = meta[i][2][0][0].attrib.get('src') #element[7][2][2][0][0].attrib['src']
						url   = meta[i][7][0].attrib.get('href') #element[7][2][7][0].attrib['href']
						entry = [name,image,url]
						out.append(entry)
				return out


	
			items=parsecatalogfile()
			items.reverse()

			for i in items:
				#print i

				url="http://robe.cz/"+ i[1]
				url=url.replace(' ','_')
				#root.reqcntr=UrlRequest(\
				#	url,\
				#	timeout = 10,\
				#	on_success = on_success2,\
				#	on_progress = on_progress2,\
				#	on_error = on_error2,\
				#	)
				#reqcntr+=1
				#root.downloading+=1
				#item8.desc="...downloading " + str(root.downloading)
				#downloadimage.update("image-loading.gif")
					

				url="http://robe.cz/"+ i[2]
				#print url

				if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
					if root.check_new_manuals=="0":
						pass
					else:
						try:
							root.reqcntr=UrlRequest(\
								url,\
								timeout = 10,\
								on_success = on_success_head,\
								on_progress = on_progress2,\
								on_error = on_error_head,\
								method='HEAD',\
								)
						except:
							pass

				else: #-----
					
					#print "must download", 
					#print btnimage
					try:
						
						root.reqcntr=UrlRequest(\
							url,\
							timeout = 20,\
							on_success = on_success_pdf,\
							on_progress = on_progress2,\
							on_error = on_error2,\
							)
							
						#print root, root.reqcntr
						root.downloading+=1
						item8.desc="...downloading " + str(root.downloading)
						downloadimage.update("image-loading.gif")
					except:
						pass
				
			#--------------------------------
		
		

		settings.bind(on_config_change=self.change_reported)

		def openweb(button, url="market://details?id=org.linuks.norbert"):
			url=url
			#print "open ", url
			#from jnius import cast
			#from jnius import autoclass
			
			#PythonActivity = autoclass('org.renpy.android.PythonActivity')
			#Intent = autoclass('android.content.Intent')
			#Uri = autoclass('android.net.Uri')
			#intent = Intent()
			#intent.setAction(Intent.ACTION_VIEW)
			#intent.setData(Uri.parse(url))
			#currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			#currentActivity.startActivity(intent)
			
			import webbrowser
			webbrowser.open(url) 

			

		def openshare(button):
			url="Check out Norbert on Google Play! https://play.google.com/store/apps/details?id=org.linuks.norbert"
			try:
				#pass
				subject=items[0]
			except:
				pass
			#subject=items[0]

			from jnius import cast
			from jnius import autoclass
			
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			intent = Intent()
			intent.setType("text/plain");
			intent.setAction(Intent.ACTION_SEND)
			
			#intent.putExtra(Intent.EXTRA_SUBJECT, "Check this out" + subject)
			try:
				#pass	
				intent.putExtra(Intent.EXTRA_SUBJECT, "Meet Norbert, unofficial ROBE lighting app")
			except:
				pass
			intent.putExtra(Intent.EXTRA_TEXT, url)
			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)



		def remove_files(self,start_path = TEMP_DOWNLOAD_PATH):
			for dirpath, dirnames, filenames in os.walk(start_path):
				for f in filenames:
					fp = os.path.join(dirpath, f)
					os.remove(fp)
					get_size()
			

		def get_size(*args):
			start_path = TEMP_DOWNLOAD_PATH
			total_size = 0
			for dirpath, dirnames, filenames in os.walk(start_path):
				for f in filenames:
					fp = os.path.join(dirpath, f)
					total_size += os.path.getsize(fp)
			total=str(total_size/(1048576))
			item4.desc="using "+total+"MB"
			return total
		
		def rotate_screen(self):
			#print Window.rotation
			if Window.rotation==0:
				Window.rotation=90
			else: Window.rotation=0

		
		
			
		conf=ConfigParser()
		conf.read('norbert.ini')
		#print conf
		panel = SettingsPanel(title="Norbert",settings=settings,config=conf) #create instance of left side panel
		
		
		item2 = SettingTitle(panel=panel, title="Settings") #another widget in left side panel
		item3 = SettingBoolean(panel=panel, config=conf, section='usersettings',key='autodownload', title="Auto download",desc="this doesn't include files in Product Brochures") #another widget in left side panel
		item6 = SettingBoolean(panel=panel, config=conf, section='usersettings',key='check_new_manuals', title="Auto update",desc="check for and get newer files when available") #another widget in left side panel
		
		item1=SettingMyItem(panel=panel, title="Review Norbert", desc="on Google Play store")
		reviewbutton = Button(text="Review Now")
		reviewbutton.bind(on_press=openweb) #bind that button to function
		item1.add_widget(reviewbutton) #add widget to item1 in left side panel

		itemshare=SettingMyItem(panel=panel, title="Share", desc="Share Norbert")
		sharebutton = Button(text="Share Now")
		sharebutton.bind(on_press=openshare) #bind that button to function
		sharebutton.bind(on_press=lambda widget, items="menu-sharenorbert": save_info(items))
		
		itemshare.add_widget(sharebutton) #add widget to item1 in left side panel

		
		item4=SettingMyItem(title="Data usage")
		
		erasebutton = Button(text="Erase!")
		erasebutton.bind(on_press=remove_files) #bind that button to function
		sizebutton = Button(text="Refresh")
		sizebutton.bind(on_press=get_size) #bind that button to function

		item4.desc="using " + get_size()+"MB"
		#eraselabel.text=erasetext
		#item4.add_widget(eraselabel)
		item4.add_widget(sizebutton) #add widget to item1 in left side panel


		item7=SettingMyItem(title="Erase all downloaded files", desc="clean the app cache but keep this app")
		
		erasebutton = Button(text="Erase!")
		erasebutton.bind(on_press=remove_files) #bind that button to function
		item7.add_widget(erasebutton) #add widget to item1 in left side panel


		item8=SettingMyItem(title="Download/update all files", desc="will take a long time")

		downloadbutton=Button(text="Download", pos_hint={'x':0, 'y':0})
		downloadimage=MyImage(source="dot.png",size_hint=(.5,.5),allow_stretch=False,pos_hint={'x':-.1, 'y':.25}) #
		wid=FloatLayout()
		wid.add_widget(downloadbutton)
		wid.add_widget(downloadimage)
		item8.add_widget(wid)


		downloadbutton.bind(on_press=download_all) #bind that button to function
		
		
		
		
		#item8.add_widget(downloadimage) #add widget to item1 in left side panel
		#item8.add_widget(downloadbutton) #add widget to item1 in left side panel


		item5 = SettingBoolean(panel=panel, config=conf, section='usersettings',key='autorotate', title="Screen rotation",desc="rotate at startup") #another widget in left side panel
		item_small_screen = SettingBoolean(panel=panel, config=conf, section='usersettings',key='small_screen', title="Phone screen",desc="adjust for small displays") #another widget in left side panel
		
		#rotatebutton = Button(text="Rotate")
		#rotatebutton.bind(on_release=rotate_screen) #bind that button to function
		#item5.add_widget(rotatebutton) #add widget to item1 in left side panel
		
		
		
		#item5=SettingMyItem(panel=panel, title="XXX",desc="yyy") #another widget in left side panel
		
		
		panel.add_widget(item1) # add item1 to left side panel
		panel.add_widget(itemshare) # add item1 to left side panel
		
		
		panel.add_widget(item2) # add item1 to left side panel
		panel.add_widget(item_small_screen) # add item2 to left side panel
		panel.add_widget(item5) # add item2 to left side panel

		panel.add_widget(item3) # add item2 to left side panel
		panel.add_widget(item6) # add item2 to left side panel
		
		panel.add_widget(item4) # add item2 to left side panel
		panel.add_widget(item8) # add item2 to left side panel
		panel.add_widget(item7) # add item2 to left side panel
		
		
		


		settings.add_widget(panel) #add left side panel itself to the settings menu


	

	def hook_keyboard(self, window, key, *largs):
		#print key
		#try:
		#	print self.settings_panel.menu
		#except:
		#	pass
			
			
		if key==292:
			
			#Window.rotation+=90
			pass
		if key == 27:
			#Cache.print_usage()
			#Cache.remove('kivy.texture')
			#Cache.print_usage()
			
			closing=self.close_settings()
			
			if closing:
				return True
			
		   # do what you want, return True for stopping the propagation
			if sm.current_screen.name=='itemmenu':
				
				if root.small_screen=="0" and root.autorotate=="0" :
					sm.current='menu'
				else:
					sm.current='submenu'
				
			elif sm.current_screen.name=='submenu':
				sm.current='menu'
			elif sm.current_screen.name=='menu':
				sm.current='topmenu'
			elif sm.current_screen.name=='article':
				sm.current='topmenu'
			elif sm.current_screen.name=='calendar':
				sm.current='topmenu'
				
			elif sm.current_screen.name=='fb':
				sm.current='topmenu'

			elif sm.current_screen.name=='catalogs':
				sm.current='topmenu'
				
			else:
				sm.current='topmenu'
				#self.call_home(end=True)
				App.stop(self)
				
		
				#tady dopln ukonceni
				
			return True 
			
	def get_file(self,items):
		url="http://robe.cz"+ items[1]['smlImageUri']
		#print url
		image=MyImage(source="image-loading.gif")
		#progress
		def on_progress1(req, cur_sz, tot_sz):
			#print req, cur_sz, tot_sz
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success1(req, result):
			#print "success"
			#print "result size", len(result)
			#print req.resp_status
			#print req
			url=TEMP_DOWNLOAD_PATH+url.split('/')[-1]
			#url=url.replace(' ','_')
			if len(result) > 0 and req.resp_status ==200:
				f = open(url,'w')
				f.write(str(result))
				f.close()
				#image=MyImage(source="b/"+url.split('/')[-1])
				image.update(url)
			else:
				image.update("fail.png")

			
		def on_error1(req, *args):
			#print 'erro on_request:', req
			req.widget.background_normal="fail.png"
		
		
		url=url.replace(' ','_')	
		if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
			image=MyImage(source=TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			
		else:
			#p=self.q.push([url, "b/"+url.split('/')[-1]])
			try:
				self.ra=UrlRequest(\
					quote(url, safe="%/:=&?~#+!$,;'@()*[]"),\
					timeout = 10,\
					on_success = on_success1,\
					on_progress = on_progress1,\
					on_error = on_error1
					)
			except:
				pass
				
		content2 = BoxLayout(orientation='vertical',spacing=10)
		content = BoxLayout(orientation='vertical',size_hint_y=.7)
		#change show time
		#change number of items
		labelNb = Label(text='')
		#content.add_widget(labelNb)
		content.add_widget(image)		
		
		content2.add_widget(content)

		replay = Button(text='Close')
		action = BoxLayout(orientation='horizontal',size_hint_y=.2)
		action.add_widget(replay)
		content2.add_widget(action)

		popup = Popup(title='%s' %items[1]['title'],
							  content=content2,
							  size_hint=(0.5, 0.5),pos_hint={'x':0.25, 'y':0.25},
							  auto_dismiss=True)
		replay.bind(on_press=popup.dismiss)
		popup.open()
		
		

#	def get_file2(self, items, *args):
#			#petrpetr
#			url="http://robe.cz" + items[1]['smlImageUri']
#			p=self.q.push([url, TEMP_DOWNLOAD_PATH+url.split('/')[-1]])
			
			
			
			
			
			
			
			
	def display_itemmenu(self,items):
		
		url=""
		
		#print items.keys()
		content = BoxLayout(orientation='vertical',spacing=6, size_hint=(1,1))
		#content=
		
		
		#content=AnchorLayout(anchor_x='right', anchor_y='bottom')
		itemmenu.content.clear_widgets()
		#itemmenu.remove_widget(content)
		#content.clear_widgets()
		#itemmenu.clear_widgets()
		
		#print url
		image=MyImage(source="image-loading.gif")
		#progress 1
		def on_progress2(req, cur_sz, tot_sz):
			
			#print "headers ", req.resp_headers
			#print "status ", req.resp_status
			
			#print tot_sz
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success2(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			
			#print req.resp_status
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
			#image=MyImage(source="b/"+url.split('/')[-1])
				image.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
			else:
				image.update("fail.png")
				

		def on_success_pdf(req,result):
			#print "headers ", req.resp_headers['content-length']
			#print "headers ", req.resp_headers
			
			#print req.head
			
			#print "status ", req.resp_status
			#print req.widget
			#print req
			#print "stahl pdf"
			url=req.url
			#url=url.replace(' ','_')
			#print req.resp_status
			if len(result) > 0 and req.resp_status == 200:
				f = open(FILE_DOWNLOAD_PATH + url.split('/')[-1],'w')
				#f = open("/storage/sdcard0/download/"+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
				req.widget.update("done.png")
				#print "saving ", req.widget
				try:
					if req.head:
						req.head.bind(on_press=lambda widget, items=str(url.split('/')[-1]): openpdf(items))
						req.head.unbind(on_press=req.head._getpdf)
						
				except:
					pass

				
				
			else:
				req.widget.update("fail.png")
				#print "not saving"
				#content.remove_widget(req.widget)
			#print "leaving on_success_pdf"
			#image=MyImage(source="b/"+url.split('/')[-1])
			#image.update("b/"+url.split('/')[-1])
			######


		def on_success_head(req,result):
			#print "headers ", req.resp_headers['content-length']
			
			try:
				online_file_size=req.resp_headers['content-length']

				url=req.url
				#url=url.replace(' ','_')
				local_file_size=os.stat(FILE_DOWNLOAD_PATH + url.split('/')[-1]).st_size
				#print 'online_file_size', int(online_file_size)
				#print 'local_file_size ', int(local_file_size)
				
				if int(local_file_size) == int(online_file_size):
					#same, do nothing
					pass
				else:
					#different sizes, get new file
					req.widget.update("image-loading.gif")
					root.reqcntr=MyUrlRequest(\
						url,\
						timeout = 10,\
						on_success = on_success_pdf,\
						on_progress = on_progress2,\
						on_error = on_error_btn,\
						widget=req.widget)
			
			except:
				pass
			


		def on_error_head(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			pass
			
			
		def on_error2(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			req.widget.update("logo.png")

		def on_error_btn(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			req.widget.update("fail.png")
					
		
		def openpdf(url):
			
			save_info("file-"+url)
			
			from jnius import cast
			from jnius import autoclass
			#pdf="/storage/sdcard0/download/" +url
			# import the needed Java class
			url=url.replace(' ','_')
			url="file://" + FILE_DOWNLOAD_PATH + url
			#print "normalized ", url
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			Uri = autoclass('android.net.Uri')

			# create the intent
			intent = Intent()
			intent.setAction(Intent.ACTION_VIEW)
			target=Uri.parse(url)
			intent.setDataAndType(target, "application/pdf")

			# PythonActivity.mActivity is the instance of the current Activity
			# BUT, startActivity is a method from the Activity class, not our
			# PythonActivity.
			# We need to cast our class into an activity, and use it
			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)
		
		def openpicture(src):
			src="file://" + FILE_DOWNLOAD_PATH + src
			
			print src

			from jnius import cast
			from jnius import autoclass
			
		
			PythonActivity = autoclass('org.renpy.android.PythonActivity')
			Intent = autoclass('android.content.Intent')
			Uri = autoclass('android.net.Uri')
			intent = Intent()
			
			intent.setAction(Intent.ACTION_VIEW)
			
			target=Uri.parse(src)
			intent.setDataAndType(target, "image/jpeg")

			currentActivity = cast('android.app.Activity', PythonActivity.mActivity)
			currentActivity.startActivity(intent)

		
		def opentest(url):
			pass
			
		#print "itemy", items
		#for b in items['items']:
		#print items.keys()
		
		boxy=GridLayout(cols=2,spacing=6, size_hint=(1,1))
		
		#boxy=StackLayout(orientation='lr-bt', spacing=6, size_hint=(.5,.5))
		
		
		#size_hint_x=None
		
		button_count=0
		for c in items.keys():
			#print items
			#print "c", c
			
			if c=='title':
				lbl=Label(text=items['title'], font_size=20,size_hint=(1, .1))
				
				#print b[c]['label'],b[c]['url']
			elif c=='smlImageUri':
				
				imagetop=MyItemImage(source="image-loading.gif",size_hint=(1, .9))
				
				
				
				
				
				#print items['smlImageUri']
				url="http://robe.cz"+ items['smlImageUri']
				url=url.replace(' ','_')
				if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
					imagetop.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				else:
				#p=self.q.push([url, "b/"+url.split('/')[-1]])
					#print imagetop
					try:
						self.reqcntr=MyUrlRequest(\
							url,\
							timeout = 10,\
							on_success = on_success2,\
							on_progress = on_progress2,\
							on_error = on_error2,\
							widget=imagetop)
					except:
						pass
				#img=MyImage(source='')
					
				imagetop.bind(on_press=lambda widget,parms=url.split('/')[-1]:openpicture(parms))
				
			
			elif c.find('button') == 0:
				button_count+=1
				wid=FloatLayout(size_hint_y=None, size=(20,90), background_color=coloroverlay)
				
				#print c
				#print "working on ", str(items[c]['label'])
				btn=ButtonMenu(text=str(items[c]['label']),halign='center',background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0})
				
				
				url="http://robe.cz"+ items[c]['url']
				url=url.replace(' ','_')
				#print url
				
				btnimage=ItemButtonImage(source="image-loading.gif", background_color=coloroverlay, size_hint=(.2, .7), pos_hint={'x':.009, 'y':.18}) #.01,.2
				
				#
				#print btnimage
				#btn.bind(on_press=lambda widget, items=str(url.split('/')[-1]): opentest(items))
				if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
					btnimage.update("done.png")
					btn.bind(on_press=lambda widget, items=str(url.split('/')[-1]): openpdf(items))
					if root.check_new_manuals=="0":
						pass
					else:
						#do checking here
						try:
							root.reqcntr=MyUrlRequest(\
								url,\
								timeout = 10,\
								on_success = on_success_head,\
								on_progress = on_progress2,\
								on_error = on_error_head,\
								method='HEAD',\
								widget=btnimage)
						except:
							pass

				else:
					
					#print "must download", 
					#print btnimage
					
					if root.autodownload=="1":
						try:
							
							root.reqcntr=MyUrlRequest2(\
								url,\
								timeout = 10,\
								on_success = on_success_pdf,\
								on_progress = on_progress2,\
								on_error = on_error_btn,\
								widget=btnimage,\
								head=btn)
						except:
							pass
						#print root, root.reqcntr
					else: 
						#must download manually
						btnimage.update('get.png')
						#print "must download", 
						#print btnimage
						
						def getpdf(args):
							url=args[0]
							widget=args[1]
							btn=args[2]
							#if os.path.isfile(FILE_DOWNLOAD_PATH + url.replace(' ','_').split('/')[-1]):
							#	#workaround for not being able to unbind getpdf
							#	pass
							#else:
							try:
								self.reqcntr=MyUrlRequest2(\
								url,\
								timeout = 20,\
								on_success = on_success_pdf,\
								on_progress = on_progress2,\
								on_error = on_error_btn,\
								widget=widget,\
								head=btn
								)
								widget.update('image-loading.gif')
							except:
								pass

						btn._getpdf=lambda widget, items=(str(url),btnimage,btn): getpdf(items)
						btn.bind(on_press=btn._getpdf)
						
					
					
						
				wid.add_widget(btn)
				wid.add_widget(btnimage)
				boxy.add_widget(wid)

		if button_count ==1:
			btn.text_size={Window.width,None}
			btnimage.pos_hint={'x':-.01, 'y':.18}
		#print boxy.height
		#print boxy.pos
		
		content.add_widget(imagetop) #image top
		content.add_widget(lbl) #label
		content.add_widget(boxy)
		#lbl.size_hint=(1,None)	
		
		#def on_height_change(widget, height):
			#print boxy.height, boxy.width
			#widget.pos=0,0
			#print button_count
			#boxy.height=90
			#print boxy.height
			#content.height
		
		#content.bind(height=on_height_change)
		
		#print Window.height, imagetop.height, lbl.height, boxy.height, content.height
		#print Window.width, imagetop.width, lbl.width, boxy.width, content.width
		
		
		
		itemmenu.add_widget(content)
		sm.current='itemmenu'
		 			
	def display_submenu(self,items):
		
		
		def on_progress3(req, cur_sz, tot_sz):
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success3(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			#print req.resp_status
			#print req
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
				req.widget.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				#print "updating image ", req.widget
			else:
				req.widget.update("logo.png")
						
			
		def on_error3(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			#print "submenu image error", req
			req.widget.update("logo.png")


		text_divider=2
		if root.small_screen=="0" and root.autorotate=="0" :
			
			#animation = Animation(opacity=0, duration=2)
			#try:
			#	animation.start(root.scrollwidget)
			#except:
			#	pass
			scroll= ScrollView(size_hint=(None, None), size=(Window.width/2, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
			

		else:
			sm.current='submenu'
			submenu.content.clear_widgets()
			scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
			text_divider=1.2

		
		
		

		
		content=GridLayout(cols=1, spacing=0, size_hint_y=None)
		content.bind(minimum_height=content.setter('height'))
		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wit.add_widget(topimg)
		content.add_widget(wit)

		contentins=GridLayout(cols=1, spacing=0, size_hint_y=None)
		contentins.bind(minimum_height=contentins.setter('height'))
		content.add_widget(contentins)

		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wib.add_widget(botimg)
		content.add_widget(wib)
			

		scroll.add_widget(content)

		def presss(scroll,where):
			if where < 0.000:
			#wit.size=(Window.width,0)
				#print where,scroll.bar_width
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				#print where,scroll.bar_width
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)
				
		scroll.bind(scroll_y = presss)
		


		if root.small_screen=="0" and root.autorotate=="0" :
			try:
				menu.topcontent.remove_widget(root.scrollwidget)
				#scroll.opacity=0	
				#animation.stop(scroll)
				#animation = Animation(opacity=1, duration=1)
				#animation.start(scroll)

			except:
				pass
			
			menu.topcontent.add_widget(scroll)
			root.scrollwidget=scroll

		else:
			submenu.add_widget(scroll)	 

		wida=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imageweb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		wida.add_widget(imageweb)
		contentins.add_widget(wida)


		def go(*args):
			contentins.remove_widget(wida)

			for i in items['items']:
				
				btn_title="%s" % ("\n".join(wrap(i['title'],20)))
				#2#
				btn=ToggleButtonMenu(text=btn_title, background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0},group='items',text_size=((Window.width-15)/text_divider,None)) #ToggleButtonMenu
				btn.bind(on_press=lambda widget, items=i: self.display_itemmenu(items))
				btn.bind(on_press=lambda widget, items="products-"+i['title']: save_info(items))
				
				#print i['title']
				image=MyImage(source="image-loading.gif",size_hint_x=.2, background_color=coloroverlay, size_hint=(.7, .7),
					pos_hint={'x':.03, 'y':.2})
				wid=FloatLayout(size_hint_y=None, size=(Window.width,110), background_color=coloroverlay)
				
				url="http://robe.cz"+ i['smlImageUri']
				url=url.replace(' ','_')
				if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
					image.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				else:
					#print image
					try:
						self.i=MyUrlRequest(\
							url,\
							timeout = 10,\
							on_success = on_success3,\
							on_progress = on_progress3,\
							on_error = on_error3,\
							widget=image)
					except:
						pass
					#print "active image download ", self.i

				wid.add_widget(btn)
				
				wid.add_widget(image)
				

				contentins.add_widget(wid)
			
			
		Clock.schedule_once(partial(go), .7)




		
	def go_to_submenu(*xargs):
		sm.current='submenu'
	
	def go_to_calendar(*xargs):
		self.display_calendar()
		
	def go_to_menu(*xargs):
		sm.current='menu'
		
	def go_to_topmenu(*xargs):
		sm.current='topmenu'
		
	def go_to_calendar(*xargs):
		sm.current='calendar'
		
		
	def prepare_menu(self):
		#root.clear_widgets()
		#root=sm
		#sm.clear_widgets()
		#root.current='topmenu'
		#content = BoxLayout(orientation='vertical',spacing=0)
		

		
		menu.content.clear_widgets()

		#print "small, rotate ", root.small_screen, root.autorotate
		
		text_divider=2
		if root.small_screen=="0" and root.autorotate=="0" :
			scroll= ScrollView(size_hint=(None, None), size=(Window.width/2, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
			menu.topcontent=GridLayout(cols=2, spacing=0, size_hint_y=None)
			


		else:
			scroll= ScrollView(size_hint=(None, None), size=(Window.width, Window.height), scroll_timeout=255, scroll_distance=20,bar_width=0)
			menu.topcontent=GridLayout(cols=1, spacing=0, size_hint_y=None)
			text_divider=1.2

		menu.topcontent.bind(minimum_height=menu.topcontent.setter('height'))
		content=GridLayout(cols=1, spacing=0, size_hint_y=None)

		
		content.bind(minimum_height=content.setter('height'))

		wit=FloatLayout(size_hint_y=None, size=(Window.width,0))
		topimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wit.add_widget(topimg)
		content.add_widget(wit)

		contentins=GridLayout(cols=1, spacing=0, size_hint_y=None)
		contentins.bind(minimum_height=contentins.setter('height'))
		content.add_widget(contentins)
		
		#contentins2=GridLayout(cols=1, spacing=0, size_hint_y=None)
		#contentins2.bind(minimum_height=contentins2.setter('height'))
		widb=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imagewebb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		widb.add_widget(imagewebb)
		menu.topcontent.add_widget(widb)
		
		
		#content.add_widget(contentins2)
		

		def on_progress4(req, cur_sz, tot_sz):
			#print req.url
			Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
			pass
			#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
			
		def update_progress(*args):
			pass
		def on_success4(req,result):
			#print "req.url",req.url
			#print "result size", len(result)
			#print req.resp_status
			#print req
			url=req.url
			if len(result) > 0 and req.resp_status ==200:
				f = open(TEMP_DOWNLOAD_PATH+url.split('/')[-1],'w')
				f.write(str(result))
				f.close()
				req.widget.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				#print "updating image ", req.widget
			else:
				req.widget.update("logo.png")
						
			
		def on_error4(req, *args):
			#print "download error"
			#print req
			#print 'error on_request:', req
			#print "submenu image error", req
			req.widget.update("logo.png")


		wib=FloatLayout(size_hint_y=None, size=(Window.width,0))
		botimg=Image(size_hint=(1, 1),size=(Window.width,0),pos_hint={'x':0, 'y':0},color=[1,1,1,1])
		wib.add_widget(botimg)
		content.add_widget(wib)

			
		scroll.add_widget(content)
			
		def presss(scroll,where):
			#wit.size=(Window.width,0)
			if where < 0.000:
				#print where,scroll.bar_width
				wib.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wib)
								
				#wit.size=(Window.width,20)
			elif where > 1.000:
				#print where,scroll.bar_width
				wit.size=(Window.width,20)
				anim = Animation(size=(Window.width, 0))
				anim.start(wit)

		scroll.bind(scroll_y = presss)
		 
		menu.topcontent.add_widget(scroll)

		#if and only if we have two panel view, display the right side now as well, to have good init screen
			
		menu.add_widget(menu.topcontent)	 
		root.must_create_menu=0

		wida=WhiteCanvasFloat(size_hint_y=None, size=(Window.width,Window.height), background_color=coloroverlay,color=coloroverlay)
		imageweb=FBImage(source='image-loading.png', background_color=coloroverlay, size_hint=(0, 0),pos_hint={'x':0.45, 'y':.45},allow_stretch=False)
		wida.add_widget(imageweb)
		contentins.add_widget(wida)

		
		def go(args):
			contentins.remove_widget(wida)
			menu.topcontent.remove_widget(widb)
		


			pl = plistlib.readPlist('dataWithId')
			first_content=''

			for i in pl.values()[0]:
				#print i['title']
				# image:
				#pl.values()[0][0]['items'][0]['smlImageUri']
				#i[0]['items'][0]['smlImageUri']
				##btn=ButtonMenu(text=i['title'],background_color=coloroverlay, size_hint_y=None, size=(Window.width,110),size_hint=(1, 1), pos_hint={'x':0, 'y':0})
				##content.add_widget(btn)
				subproducts=i['items']
				#btn.bind(on_press=lambda widget, items=subproducts: self.get_file(items))
				btn=ToggleButtonMenu(text=i['title'], background_color=coloroverlay, size_hint=(1, 1), pos_hint={'x':0, 'y':0}, group='submenu',text_size=((Window.width/text_divider)-10,None))
				
				def crossfade(widget):
					animation = Animation(opacity=0,duration=.2)
					animation.start(root.scrollwidget)

				#btn.bind(on_press=crossfade)
				btn.bind(on_press=lambda widget, items=i: self.display_submenu(items))
				
				btn.bind(on_press=lambda widget, items="categories-"+i['title']: save_info(items))


		
				
				#for first init, display both columns
				if first_content=='':
					btn.state='down'
					first_content=i
			
				
				#btn.bind(on_press=lambda widget, items=i: self.display_itemmenu(items))
				#print i['title']
				image=MyImage(source="image-loading.gif",size_hint_x=.2, background_color=coloroverlay, size_hint=(.7, .7),
					pos_hint={'x':.03, 'y':.2})
				wid=FloatLayout(size_hint_y=None, size=(Window.width,110), background_color=coloroverlay)
				
				url="http://robe.cz"+ i['items'][0]['smlImageUri']
				url=url.replace(' ','_')
				if os.path.isfile(TEMP_DOWNLOAD_PATH+url.split('/')[-1]):
					image.update(TEMP_DOWNLOAD_PATH+url.split('/')[-1])
				else:
					#print image
					try:
						
						self.i=MyUrlRequest(\
							url,\
							timeout = 10,\
							on_success = on_success4,\
							on_progress = on_progress4,\
							on_error = on_error4,\
							widget=image)
					except:
						pass
					#print "active image download ", self.i

				wid.add_widget(btn)
				
				wid.add_widget(image)
				
				contentins.add_widget(wid)
				
			if root.small_screen=="0" and root.autorotate=="0" :
				self.display_submenu(first_content)
				
			
		Clock.schedule_once(partial(go), 1)

		
		#return root
	def display_menu(self, *xargs):
		#self.prepare_menu()
		save_info("menu-products")
		
		if root.must_create_menu==1:
			self.prepare_menu()
		sm.current='menu'

	def call_home(self,end=False):
		
		def posting_ok(req, result):
			#print len(result)
			#print req.resp_status
			if len(result) == 2 and req.resp_status ==200:
				try:
					os.remove('info.txt')
					#print "removed"
					#if end==True:
					#	App.stop(self)

					
				except:
					pass

		def posting_ko(req, result):
			#print result
			#if end==True:
			#	App.stop(self)

			pass

		try:				
			#call home
			if os.path.isfile("info.txt"):
				b=open("info.txt", mode="r")
				a=b.read()
				params = urllib.urlencode({'uid':root.rand_uid,'data':a})
				#print params
				headers = {'User-Agent' : 'norbert','Content-type': 'application/x-www-form-urlencoded','Accept': 'text/plain'}
				req = UrlRequest('http://vanous.penguin.cz/files/kivy/', on_success=posting_ok, on_error=posting_ko, req_body=params,req_headers=headers)
			else:
				#if end==True:
				#	App.stop(self)
				pass

	
		except:
			#if end==True:
			#	App.stop(self)
			pass




	def intro(self):
		
		def fetch_data_from_server(*args):
			def store_data(req, result):
				#print "got data"
				
				if len(result) > 0 and req.resp_status ==200:
					old_file_size=int(os.stat('dataWithId').st_size)
					f = open('dataWithId','w')
					f.write(str(result))
					f.close()
					new_file_size=int(os.stat('dataWithId').st_size)
					if int(old_file_size) != int(new_file_size):
						self.prepare_menu()
					#loadimage.update("done.png")
					
					
				else:
					pass
					#loadimage.update("fail.png")
					
					
				#image=MyImage(source="b/"+url.split('/')[-1])
				#image.update("b/"+url.split('/')[-1])
				#Clock.schedule_once(partial(animate), 5)
				
				#root.clear_widgets()
			def on_progress(req, cur_sz, tot_sz):
				#print req, cur_sz, tot_sz
				Clock.schedule_once(partial(update_progress, req, cur_sz, tot_sz), 1)
				pass
				#image=Image(source="/usr/local/lib/python2.7/dist-packages/kivy/data/images/image-loading.gif")
				
			def update_progress(*args):
				pass
			def on_error(req, err):
				pass
				#print 'error on_request:', req
				#loadimage.update("fail.png")
				#Clock.schedule_once(partial(animate), 5)

			#loadimage.update("image-loading.gif")
			#animate_up()
			#loadimage.color=(1,1,1,1)
			try:
				self.ro=UrlRequest('http://vanous.penguin.cz/files/kivy/dataWithId',\
					timeout = 10,\
					on_success = store_data,\
					on_progress = on_progress,\
					on_error = on_error
					)
			except:
				pass
		
		def rotate_screen(self):
			#print Window.rotation
			if Window.rotation==0:
				Window.rotation=90
			else: Window.rotation=0
				
		

		content = WhiteCanvas2(orientation='vertical',spacing=8)
		topmenu.add_widget(content)
		btn=ButtonNavi(text='Product\nCatalog', background_color=coloroverlay)
		btncalendar=ButtonNavi(text='Exhibition\nCalendar', background_color=coloroverlay)
		btnbrochures=ButtonNavi(text='Product\nBrochures', background_color=coloroverlay)
		btnmessages=ButtonNavi(text='Facebook\nUpdates', background_color=coloroverlay)
		
		
		#btnrotate=Button(size_hint=(.1,.3), pos_hint={'x':.9, 'y':0},background_color=[0,0,0,0])
		#btncalendar=Button(size_hint=(.09,.3), pos_hint={'x':.8, 'y':0},background_color=[0,0,0,0])
		
		
		#imagerotate=MyImage(source="rotate.png", background_color=coloroverlay, size_hint=(.1, .3),pos_hint={'x':.90, 'y':0})
		#imgcalendar=MyImage(source="cal.png", background_color=coloroverlay, size_hint=(.6, .3),pos_hint={'x':.55, 'y':0})
		
		#btncalendar.bind(on_press=self.display_calendar)
		
		#btnrotate.bind(on_press=rotate_screen)
		#image=MyImage(source="icon.png", background_color=coloroverlay, size_hint=(.2, .2),pos_hint={'x':.72, 'y':.7})
		#wid=FloatLayout()
		#wid=BoxLayout()
		#wid.add_widget(btn)
		#wid.add_widget(image)	
		#wid.add_widget(btnrotate)	
		#wid.add_widget(imagerotate)	
		#wid.add_widget(btncalendar)	
		#wid.add_widget(imgcalendar)	
		
		

		def animate(*args):
			#print "Animating"
        # create an animation object..
			#animation = Animation(size=(500, 100))
			#animation = Animation(size=(Window.width, 100))
			animation = Animation(color=(1,1,1,0))
			
			animation.start(loadimage)

		def animate_up(*args):
			#print "Animating"
        # create an animation object..
			#animation = Animation(size=(500, 100))
			#animation = Animation(size=(Window.width, 100))
			
			#print list
			animation = Animation(color=(1,1,1,1))
			
			animation.start(loadimage)
			
			
			
			


		
		mynews=News()
		root.mynews=mynews
		root.must_create_calendar=1
		root.must_create_catalogs=1
		root.must_create_menu=1
		root.must_create_fb=1
		
		#mynews.CreateCalendar()
		#mynews.CreateCatalogs()
		#self.prepare_menu()
		mynews.CreateNews()
		
		Clock.schedule_interval(partial(mynews.getfbfile), 60*20)
		Clock.schedule_once(partial(mynews.getfbfile), 1.3)
		Clock.schedule_once(partial(mynews.getrssfile), 2) #news
		Clock.schedule_once(partial(mynews.getcalfile), 2.1) #calendar
		Clock.schedule_once(partial(mynews.getytfile), 2.2) #youtube channel
		Clock.schedule_once(partial(mynews.getcatalogsfile), 2.3) #Products Brochures
		Clock.schedule_once(partial(fetch_data_from_server), 2.4)  # fetch plist from marketing uk
		
		#mynews.getgobosfile()
	
		wit=FloatLayout(size_hint_y=None,width=0, size=(0,0))
		timg=Image(color=[0,0,0,0],size_hint_x=None,width=0)
		wit.add_widget(timg)
		content.add_widget(wit)
		content.add_widget(mynews)
		
		contentlow = BoxLayout(orientation='horizontal', size_hint=(1,.2))

		##loadimage=MyImage(source='dot.png',background_color=coloroverlay, size_hint=(1, 1),pos_hint={'x':-.2, 'y':0},color=(1,1,1,1))
		##loadimage.color=(1,1,1,0)
		def removeimage(self):
			contentlow.remove_widget(loadimage)
			return False
			
		
		#simg=Image(color=[0,0,0,0])
		#contentlow.add_widget(simg)
		
		contentlow.add_widget(btn)
		contentlow.add_widget(btnbrochures)
		contentlow.add_widget(btncalendar)
		contentlow.add_widget(btnmessages)

		btn.width=contentlow.height
		
		#simg=Image(color=[0,0,0,0])
		#contentlow.add_widget(simg)
		
		
		#contentlow.add_widget(btnrotate)
		
		#loading image
		#wid.add_widget(loadimage)
		
		root.wifb=BoxLayout(size_hint_y=.06)
		#fblabel=ButtonOptionFB(text="abc",background_color=coloroverlay)
		
		mynews.CreateFB()
		#root.wifb.add_widget(a)
		
		
		contentbelow=BoxLayout(orientation='vertical',size_hint=(1,.2))
		contentbelow.add_widget(contentlow)
		content.add_widget(contentbelow)
		contentbelow.add_widget(root.wifb)
		
		btn.bind(on_press=self.display_menu)
		btncalendar.bind(on_press=mynews.display_calendar)
		btnbrochures.bind(on_press=mynews.display_catalogs)
		btnmessages.bind(on_press=mynews.display_fb)
		save_info("app-start"+root.autorotate+root.small_screen)

		
		
		#animate()
			
		#loadimage.bind(on_touch_up=rotate)
		#not needed for testing
		
		
		#Window.rotation+=90
		
		return root

if __name__ == '__main__':
    Norbert().run()

	
	
